How to parse json array with ajax? - java

Servlet side. I write 2 JSON String objects to JSON array:
Gson data = new Gson();
JsonArray arr = new JsonArray();
JsonObject obj1 = new JsonObject();
JsonElement element = data.toJsonTree(imgstr);
obj1.add("image", element);
arr.add(obj1);
JsonObject obj2 = new JsonObject();
JsonElement element1 = data.toJsonTree(strBuf);
obj2.add("html", element1);
arr.add(obj2);
out.write(arr.toString());
Ajax. I receive that array:
done(function(result) {
console.log(result);
})
It shows [{"image":"myImageString"},{"html":"myHtmlString"}].
How to get that Strings separately? Following doesn't work:
var image=result.image;
var html=result.html;

Your result in this case in an array of objects. So you should acces them as an array:
var image=result[0].image;
var html=result[1].html;
It would be better though to just return one object:
JsonObject obj1 = new JsonObject();
JsonElement element = data.toJsonTree(imgstr);
obj1.add("image", element);
obj1.add("html", element1
out.write(obj1.toString());
In which case your suggested code
var image=result.image;
var html=result.html;
will work.

if you sending an array, you must retrieve objects from array by index like
var image=result[0].image;
But if you want to get objects by name like
var image=result.image;
you must send JsonObject not a JsonArray

Related

How to create multiple JSON array to JSON object in servlets

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

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 "\/"

Java JSON parse array

I am using the following library to parse an object:
{"name": "web", "services": []}
And the following code
import com.json.parsers.JSONParser;
JSONParser parser = new JSONParser();
Object obj = parser.parseJson(stringJson);
when the array services is empty, it displays the following error
#Key-Heirarchy::root/services[0]/ #Key:: Value is expected but found empty...#Position::29
if the array services has an element everything works fine
{"name": "web", "services": ["one"]}
How can I fix this?
Thanks
Try using org.json.simple.parser.JSONParser
Something like this:
JSONParser parser = new JSONParser();
JSONObject jsonObject = (JSONObject) parser.parse(stringJson);
Now to access the fields, you can do this:
JSONObject name = jsonObject.get("name"); //gives you 'web'
And services is a JSONArray, so fetch it in JSONArray. Like this:
JSONArray services = jsonObject.get("services");
Now, you can iterate through this services JSONArray as well.
Iterator<JSONObject> iterator = services.iterator();
// iterate through json array
while (iterator.hasNext()) {
// do something. Fetch fields in services array.
}
Hope this would solve your problem.
Why do you need parser?
try this:-
String stringJson = "{\"name\": \"web\", \"services\": []}";
JSONObject obj = JSONObject.fromObject(stringJson);
System.out.println(obj);
System.out.println(obj.get("name"));
System.out.println(obj.get("services"));
JSONArray arr = obj.getJSONArray("services");
System.out.println(arr.size());
I solve the problen with https://github.com/ralfstx/minimal-json
Reading JSON
Read a JSON object or array from a Reader or a String:
JsonObject jsonObject = JsonObject.readFrom( jsonString );
JsonArray jsonArray = JsonArray.readFrom( jsonReader );
Access the contents of a JSON object:
String name = jsonObject.get( "name" ).asString();
int age = jsonObject.get( "age" ).asInt(); // asLong(), asFloat(), asDouble(), ...
Access the contents of a JSON array:
String name = jsonArray.get( 0 ).asString();
int age = jsonArray.get( 1 ).asInt(); // asLong(), asFloat(), asDouble(), ...

How to parse a JSONArray of JSONObjects in JAVA?

I have the following array returned to my JAVA Android application from PHP:
Array ( [0] => Array ( [referral_fullname] => Name 1 [referral_balance] => 500 ) [1] => Array ( [referral_fullname] => Name 2 [referral_balance] => 500 ) );
In Java they above array looks like this:
{"0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}};
For a simple JSONObject I'm using:
JSONTokener tokener = new JSONTokener(result.toString());
JSONObject finalResult = new JSONObject(tokener);
referral_fullname = finalResult.getString("referral_fullname");
but for an array of objects I don't know!
String str = your Json-> apply to.String();
JSONObject jObject = new JSONObject(str);
Map<String,String> map = new HashMap<String,String>();
Iterator iter = jObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
String value = jObject .getString(key);
map.put(key,value);
}
Your Json Syntax is wrong , JSONArray should be like this :
["0":{"referral_fullname":"Name 1","referral_balance":"500"},"1":{"referral_fullname":"Name 2","referral_balance":"500"}];
and to parse a JsonArray that contains some JSONObject , try this :
//parse the result
JSONObject jsonResult = null;
JSONArray arrayResult = null;
ArrayList<YourObject> listObjects = null;
try {
arrayResult = new JSONArray(result);
if(arrayResult != null) {
listObjects = new ArrayList<YourObject>();
int lenght = arrayResult.length();
for(int i=0; i< lenght; i++) {
JSONObject obj = arrayResult.getJSONObject(i);
YourObject object = new YourObject(obj);
listObjects.add(object);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
And add a constructor in your Class YourObject to convert your Json to an instance :
public YourObject(JSONObject json) {
if (!json.isNull("referral_fullname"))
this.referral_fullname = json.optString("referral_fullname", null);
if (!json.isNull("referral_balance"))
this.referral_balance = json.optString("referral_balance", null);
}
You should use
JSONArray finalResult = new JSONArray(tokener);
if you can. You structure is now an object with two fields, 0 and 1, which contains another object. You have to get an array of object in place of this composite object if you want to iterate easily like
JSONObject jso;
for(int i = finalResult.lenght-1; i >=0; i--){
jso = finalResult.get(i);
// jso == {"referral_fullname":"Name 1","referral_balance":"500"}
[whatever]
}
Try this.............
final JSONArray result_array = json.getJSONArray("result");
for (int i = 0; i < result.length(); i++) {
JSONObject joObject = result_array.getJSONObject(i);
String jName = joObject.get("referral_fullname").toString();
String jbalance = joObject.get("referral_balance").toString();
}
First make an JSON object and see then in inner level what you have if you have array then fetch array.
You need to make JSON object first. For example, if resp is a String (for example coming as http response)
JSONObject jsonObject = new JSONObject(resp);
jsonObject may contains other JSON Objects or JSON array. How to convert the JSON depends on the response.
If arraykey is a array inside the JSON objects then we can get list of array by the following way.
JSONArray arr = jsonObject.getJSONArray("arraykey");
Check the length of arr, if it is greater than 0 then it contains JSON objects or JSON array depending the data.
There is a complete example with some explanation about JSON String to JSON array can be found at
http://www.hemelix.com/JSONHandling

Categories