How to create multiple JSON array to JSON object in servlets - java

I need to create variable amount of JSON objects and based on the result set from a database query. States retrieving from mysql database. I am saving the response in JSON array but it is saving in multiple JSON objects like that:
jString userid = rs2.getString("state");
JSONObject mainObj = new JSONObject();
JSONArray jsArray = new JSONArray();
jsArray.put(userid );
mainObj.put("states", jsArray);
With this output:
{"states":["karnataka"]}
{"states":["kerala"]}
{"states":["chennai"]}
Can I get output in single JSON object like {"States":"karnataka","kerala","chennai"}?

You probably just got some code structure confused.
Try something like this:
JSONArray jsArray = new JSONArray();
JSONObject mainObj = new JSONObject();
//some kind of loop
{
jString userid = rs2.getString("state");
jsArray.put(userid);
}
mainObj.put("states", jsArray);

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");
}
}

Creating json in java getting only first value not getting as desired format

I want to create a json array which looks like follows:
[{"label":"Organisation 1","ID":2},{"label":"Organisation 2","ID":1},....]
I did as follows :
JSONObject obj = new JSONObject();
while (rstcust.next()) {
obj.put("label", rstcust.getString(3));
obj.put("ID", rstcust.getInt(1));
}
out.print(obj);
I am getting only first value as output I am not getting like the fomat above:
I am getting the following output
{"label":"Organisation 1","ID":2}
This is happening because you are creating a JSONObject but what you need is a JSONArray
Create a JSONArray Object and then add individual JSONObjects into it.The code will be something like this.
JSONArray arr = new JSONArray();
while (rstcust.next()) {
JSONObject obj = new JSONObject();
obj.put("label", rstcust.getString(3));
obj.put("ID", rstcust.getInt(1));
arr.put(obj);
}
out.print(arr);
The JavaDocs for JSONArray can be found here.
In java 6 org.json.JSONArray contains the put method and in java 7 javax.json contains the add method.

Java how can I get a row of Json data outside of the for loop

I am using java to create a web service with Json and am really stumped on a particular area. I have a Jsonarray and JsonObject that reads Json in a for loop, but now how can I for example select items in the second row of the Json outside of the for loop? Perhaps an example of my code will help, my json list is dynamic but this is the format
[{"state":"LA","city":"Kisatchie"},{"state":"KS","city":"Kismet"}]
Now I read the json above with this code
// the total String has the whole Json data
JSONObject jsonn = new JSONObject(total);
JSONArray jArray = jsonn.getJSONArray("location_update");
JSONObject jobject = null;
String city="";String state="";
JSONArray sss = new JSONArray();
for (int i = 0; i < jArray.length(); i++) {
jobject = jArray.getJSONObject(i);
city+= jobject.getString("city");
state+= jobject.getString("state");
sss.put(jobject);
}
// How can I for example get Row 2 of Json here outside the for loop
// Row 2 is this data
// {state":"KS","city":"Kismet"}
I need this because some of that data in the Json above is used for a dropdown selection menu and as soon as the user clicks on an item I would like to show all the information on that row of Json. I obviously have many more Json items than what I displayed above. I do know that this jobject = jArray.getJSONObject(i); is numbering items but I do not know how I can pull that out of the for loop any suggestions would be great
As Java starts numbering at 0, selecting the second array element looks like the following:
JSONArray jArray = jsonn.getJSONArray("location_update");
JSONObject jobject = jArray.getJSONObject(1);
Did you try this outside for loop
JSONObject jsonObject = jArray.getJSONObject(1);
By the way I will prefer to use Jackson library and map my json directly to some class. You can refer this example by #mkyong.
If you want the second object in the array:
JSONObject jsonn = new JSONObject(total);
JSONArray jArray = jsonn.getJSONArray("location_update");
jobject = jArray.getJSONObject(1);
If you already have jsonn or jArray in scope, then you only need:
jobject = jArray.getJSONObject(1);

Need to change my code to generate correct JSON object

I am trying to generate the following JSON to be accessed by tokenInput, but my code generates it in other way, how can I tailor the code to generate the correct JSON.
Required Json
get[{id:"set",name:"set"},{id:"object",name="object}]
or
[{id:"set",name:"set"},{id:"object",name="object}]
My JSON
{"get":[{"id":"set","name":"set"},{"id":"object","name":"object"}]}
MyCode
JSONObject res = new JSONObject();
JSONArray jarray = new JSONArray();
JSONObject object = new JSONObject();
object.put("id","set");
object.put("name", "set");
jarray.add(object);
JSONObject object1 = new JSONObject();
object1.put("id","object");
object1.put("name", "object");
jarray.add(object1);
res.put("get", jarray);
return res;
JSP
$(document).ready(function() {
$("#items").tokenInput("getOptions.jsp",{
theme: "facebook"
});
});
[{"id":"set","name":"set"},{"id":"object","name":"object"}]
this can be only form can get instead of form ur code generates . make res a JSONArray . then try .. !

Categories