Reputation: 1305
I'm trying to pass a javascript array of items to a java server using JSON. my server receives the following String:
[
{"attr1":"SomeValue1","attr2":"SomeValue2"},
{"attr1":"SomeValue3","attr2":"SomeValue4"}
]
I'm trying to use JsonArray
, but am probably doing it wrong (I'm not adding my code here since it is probably just stupid).
Can anyone give me the proper way of creating an iterating over the values from my String?
Edit: as requested, my stupid code:
jsnobject = new JSONObject(items); //items is the string described above
JSONArray jsonArray = jsnobject.getJSONArray("");
if(jsonArray != null){
for(int i=0 ; i<jsonArray.length();i++){
JSONObject explrObject = jsonArray.getJSONObject(i);
System.out.println("name = "+explrObject.get("fileName"));
}
}
Upvotes: 0
Views: 1920
Reputation: 66
You can use J SON Serialize method you can pass the j son string ...
Upvotes: 0
Reputation: 371
I've never used JsonArray(previously I've used gson to go between json and Java), but looking at the documentation
It looks like you can create the JsonArray by passing in a correct json string into the constuctor. Then you should be able to iterate through it like a typical array.
JsonArray myArray = new JsonArray(jsonString);
int length = myArray.length();
for(int i=0; i<length; i++){
myArray.get(i)
//note this returns an object of type object,
//use other get functions to get other types
}
Upvotes: 2
Reputation: 725
JSON.stringify(array)
without your code it is hard to see what you are wanting but this is how you convert js array to a JSON obj
Upvotes: 0