Convert Json array "[{}]" to "[]" in Java - java

I want to convert my Blank Json array to the Null Json array.
For ex., My Json array is like "[{}]" and if I got this array then automatically converts to "[]".
My code is like as below :
JsonObject jo = FetchData.getAllItemsAvg(request.getParameter("where"), request.getParameter("lastNum"),request.getParameter("limitAvgNum"));
JsonArray ja = new JsonArray();
ja.add(jo); // Some times ja like "[{}]" .

Check if the object is empty before adding it to the array.
(assuming you're using JsonObject):
JsonObject jo = FetchData.getAllItemsAvg(
request.getParameter("where"),
request.getParameter("lastNum"),
request.getParameter("limitAvgNum"));
JsonArray ja = new JsonArray();
if(!jo.isEmpty()){
ja.add(jo);
}
For com.google.gson.JsonObject:
JsonObject jo = FetchData.getAllItemsAvg(
request.getParameter("where"),
request.getParameter("lastNum"),
request.getParameter("limitAvgNum"));
JsonArray ja = new JsonArray();
if(!jo.entrySet().isEmpty()){
ja.add(jo);
}

Related

Read out nested JSONObject with Java. Don't get the inner JSONObject

I'm trying to read a JSONObject from within another JSONObject. The first output works, the second, i.e. the JSONObject within, does not. Here I get the following error
org.json.JSONException: JSONObject["Values"] not found.
This is the output of the first object / array
ergebnis: {"Description":"","Objects":[{"RefStr":"76-1044-0","ClassName":"Application","Values":{"providerorg-refstr":"262-462-0",...}]}
This is how I try to get the data:
JSONObject jsonObject = new JSONObject(ergebnis);
System.out.println(jsonObject);
JSONObject inside = jsonObject.getJSONObject("Values");
System.out.println(inside);
Values object is present in Objects. This objects is an array. You can try like below,
JSONObject jsonObject = new JSONObject(json);
System.out.println(jsonObject);
JSONObject jsonObject1= jsonObject.getJSONObject("ergebnis");
System.out.println(jsonObject1);
JSONArray objects = jsonObject1.getJSONArray("Objects");
System.out.println(objects);
JSONObject inside = objects.getJSONObject(0).getJSONObject("Values");
System.out.println(inside);

Json array inside array retrieve values Android

i m trying to get values from JSONArray inside array, i m able to retrieve whole JSON values into JSONArray successfully but not able to retrieve values inside JSONArray. When i convert JSONArray to JSONObject to get values stored inside JSONArray. It gives error: org.json.JSONException: No value for "banner"
Here is JSON code, i verified JSON code with jsonlint.com and it showed JSON is Validate,
[
{"code":"banner","moduletitle":0,
"banner":
[
{"image":"http://imageurl"},
{"image":"http://imageurl"},
{"image":"http://imageurl"}
]
}
]
I m trying to get this from 3 hour but no luck. i m new in JSON and do not know how JSON Actually work, and also read abut GSON Library to get JSON values. here is My Java code.
JSONArray jsonObj = null;
String image_url = "";
String banner_code ="";
try {
jsonObj =new JSONArray(lib_function.getJSONUrl( jsontags.Top_Banner_JOSN_URLs));
Log.d("value retrun :","" +jsonObj);
//---vlaue is coming and print in Log ----//
} catch (JSONException e) {
Log.v("Error in Parser :", " " + e);
Log.d("no value retrun :", "failed to convert");
}
try{
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName", jsonObj);
JSONArray subArray = jo.getJSONArray("banner");
image_url= subArray.getString(Integer.parseInt("image"));
Log.d("banner code",""+subArray);
}catch(Exception e)
{
Log.d("not working",""+e);
}
I folllow this question but luck:
How to parse JSON Array inside another JSON Array in Android
If anyone suggest, what i m doing wrong will be appreciate. or let me know, where i can get more information about json
UPDATE thanks too all to give their precious time for answering my stupid question. All answers are correct , but i can accept only one answer. A Big thanks to all
Here:
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName", jsonObj);
Because parsing jsonObj JSONArray so no need to create new JSONArray and JSONObject to extract it from jsonObj. remove all above three lines.
banner JSONArray is inside JSONObject which is contained by jsonObj JSONArray, get it as:
JSONObject jsonObject=jsonObj.optJSONObject(0);
JSONArray subArray = jsonObject.getJSONArray("banner");
// get code key from `jsonObject`
String strCode=jsonObject.optString("code");
// get all images urls from `subArray`
for(int index=0;index<subArray.length();index++){
JSONObject imgJSONObject=subArray.optJSONObject(index);
// get image urls
String strImgURL=imgJSONObject.optString("image");
}
Also, if jsonObj JSONArray contains multiple JSONObject's then use for-loop to iterate it.
I am assuming you have the rest of the values accessible to you, so posting just this snippet.
code=jsonObject.getString("code");
moduletitle=jsonObject.getString("moduletitle");
banner=jsonObject.getJSONArray("banner");
jsonObj =new JSONArray(lib_function.getJSONUrl( jsontags.Top_Banner_JOSN_URLs);
From above line you will get JSONArray. So now loop it and get you banner JSONArray.Again loop bannerArray and you will get image Urls
If You want value of "image" which is in json arrray than
String response = "your response";
try{
JsonArray jAry = new JsonArray(response);
JsonObject jObj = jAry.getJsonObject(0);
JsonArray jsonBanner = jObj.getJsonArray("banner");
JsonObject temp;
for(int i=0;i<jsonBanner.length;i++){
temp = jsonBanner.getJsonObject(i);
String image = temp.optString("image");
}
}

JSON - Create JSONObject with array

I need to create in a Java (Android) a JSONObject/JSONArray with the exact following structure:
{
"listId":
[
"c02bc683-fcd7-47a5-b157-853e26ed099e",
"f8e1c9d7-ae45-4433-a315-726c1d912d09"
]
}
Can somebody help me on this please?
EDIT:
What i have is this:
JSONArray obj = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("listId", folderId);
obj.put(jsonObject);
JSONObject json = new JSONObject();
json.put("id", obj);
But this produces something like:
{
"listId":
[
{"id":"c02bc683-fcd7-47a5-b157-853e26ed099e"},
{"id":"f8e1c9d7-ae45-4433-a315-726c1d912d09"}
]
}
Thanks
You've got your array creation a bit mixed up. What you really want is an object holding an array of string, but what you're doing is creating an array of JSONObject.
Try this instead:
String[] arr = { "c02bc683-fcd7-47a5-b157-853e26ed099e", "f8e1c9d7-ae45-4433-a315-726c1d912d09" };
JSONArray jsonArray = new JSONArray(arr);
JSONObject json = new JSONObject();
json.put("listId", jsonArray);
System.out.println(json); // {"listId":["c02bc683-fcd7-47a5-b157-853e26ed099e","f8e1c9d7-ae45-4433-a315-726c1d912d09"]}

double quote in json simple

I want this outcome:
{"link":[{"url":"http://en.wikipedia.org/wiki/JScript", "label":"wikipedia"}]}
I tried this:
JSONObject ob1 = new JSONObject();
ob1.put("link","[{\"url\":\"http://en.wikipedia.org/wiki/JavaScript\", label:\"wikipedia\"}]");
The output of ob1.toJSONString() is:
{"link":"[{\"url\":\"http:\/\/en.wikipedia.org\/wiki\/JavaScript\", label:\"wikipedia\"}]"}
What am I doing wrongly?
I am using json-simple-1.1.1
You should put a JSONArray into the JSONObject and in the Array again a JSONObject with the keys/values "url"/"http://en.wikipedia.org/wiki/JScript" and "label"/"wikipedia"
JSONObject ob1 = new JSONObject();
JSONArray ar1 = new JSONArray();
ob1.put ("link", ar1);
JSONObject ob2 = new JSONObject();
ar1.add(ob2);
ob2.put("url", "http://en.wikipedia.org/wiki/JScript");
ob2.put("label", "wikipedia");
In case you have the value of ob1 link object already as JSON string then you can first interpret this into a JSONArray using
JSONArray ar1 = (JSONArray)JSONValue.parse(yourJSONStr);
NOTE: Your intended result is not a JSON string, because for that all "/" must be escaped "\/"

Issue With JSON Object in Java?

I have a JSON Object which converted into String and saved into database .But when i am trying to get it back it is throwing exception.My object is something like that...
{"COLUMN":["Type","Sub Type","F.P.","P.P.","Process","Due To Start"]}
How can we get the data back in Normal form?
My Java Code is.....
JSONObject obj = new JSONObject();
JSONArray the_json_array = obj.getJSONArray(userReorderOption);
int size = the_json_array.size();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
arrays.add(another_json_object);
}
And Exception i am getting....
net.sf.json.JSONException: JSONObject["{\"TASKLIST_COLUMN_REORDER\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}"] is not a JSONArray.
And this is java Code how i am creating JSON Object and saving into database...
String userReorderSelection;
Set set = new LinkedHashSet(userReorderSelection);
JSONObject json = new JSONObject();
json.accumulate("COLUMN", set);
saveJSONObj("PrimaryKeyColumn", json.toString());
Thanks Tichodroma,
But as i told i am using net.sf.json.JSONObject class and above things we can achieve from this class too..What i did to solve the above issue?...Please have a look on the Java code...
JSONObject jsonObj = new JSONObject();
JSONObject obj = jsonObj.fromObject(userReorderOption);
JSONArray columnName = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < columnName.size(); i++) {
System.out.println(columnName.getString(i));
}
This code work fine for me with my Json Jar**(net.sf.json)**
Your JSON is not a JSONArray.
A JSONArray is an ordered sequence of values.
You have a JSONObject.
A JSONObject is an unordered collection of name/value pairs.
Edit:
Using the JSON implementation from org.codehaus.jettison.json, you can do this:
String json = "{\"COLUMN\":[\"Type\",\"Sub Type\",\"F.P.\",\"P.P.\",\"Process\",\"Due To Start\"]}";
JSONObject obj = new JSONObject(json);
JSONArray column = (JSONArray) obj.get("COLUMN");
for (int i = 0; i < column.length(); i++) {
final String field = column.getString(i);
System.out.println(field);
}
Result:
Type
Sub Type
F.P.
P.P.
Process
Due To Start

Categories