Convert string to JsonArray

how to convert this string to jsonArray correctly?

{ "myArray": [ { "id": 1, "att1": 14.2, "att2": false }, { "id": 2, "att1": 13.2, "att2": false }, { "id": 3, "att1": 13, "att2": false } ]} 

An JSONArray jArray = new JSONArray(STRING_FROM_ABOVE); leads to jArray.length = 1 Its the first time to contact json :)

+7
java json android
source share
4 answers

Try the following:

 JSONObject jObject = new JSONObject(STRING_FROM_ABOVE); JSONArray jArray = jObject.getJSONArray("myArray"); 

"string_from_above" is not a Json array, it is a Json object containing one attribute (myArray), which is a Json Array;)

Then you can:

 for (int i = 0; i < jArray.length(); i++) { JSONObject jObj = jArray.getJSONObject(i); System.out.println(i + " id : " + jObj.getInt("id")); System.out.println(i + " att1 : " + jObj.getDouble("att1")); System.out.println(i + " att2 : " + jObj.getBoolean("att2")); } 
+10
source share

During parsing, add values ​​for objects and ArrayLists or, however, how you want to use them. Good luck.

 JSONObject jo = new JSONObject(STRING_FROM_ABOVE); JSONArray rootArray= jo.getJSONArray("myArray"); int rootArrayLength=rootArray.length(); for(int i=0;i<rootArrayLength;i++){ int id= rootArray.getJSONObject(i).getInt("id"); // do same for others too and create an object } // create object and make a list 
+2
source share

To just add another method to the mix, I would recommend taking a look at Gson . Gson is a library that simplifies serialization and deserialization from Java objects. For example, with your line, you can do this:

 // Declare these somewhere that is on the classpath public class ArrayItem{ public int id; public double att1; public boolean att2; } public class Container{ public List<ArrayItem> myArray; } // In your code Gson gson = new Gson(); Container container = gson.fromJson(json, Container.class); for(ArrayItem item : container.myArray){ System.out.println(item.id); // 1, 2, 3 System.out.println(item.att1); // 14.2, 13.2, 13.0 System.out.println(item.att2); // false, false, false } 

Similarly, you can also go back very easily.

 String jsonString = gson.toJson(container); // jsonString no contains something like this: // {"myArray":[{"id":1,"att1":14.2,"att2":false},{"id":2,"att1":13.2,"att2":false},{"id":3,"att1":13.0,"att2":false}]} 

The main advantage that uses something like Gson is that you can now use all the default Java type checking, instead of having to manage attribute names and types yourself. It also allows you to do some fancy things, such as hierarchies of replication types, which make it easy to manage a lot of json messages. It works great with Android, and the jar itself is tiny and does not require any additional dependencies.

+1
source share

Take a look at jQuery, and in particular the Parse function. This will directly parse the Json array into the object.

0
source share

All Articles