简体   繁体   中英

Parsing JSON ARRAY

I'm working on json parsing and I got a problem. This is my JSON:

"cards":[
{
"id":"bgyr6gh5yr6154",
"checkItemStates":[
],
"closed":false,
"desc":"",
"due":"2012-06-13T10:00:00.000Z",
"idBoard":"4v454g5r1515",
"idChecklists":[
],
"idList":"16562562526",
"idMembers":[
"2848f4g85t15"
],
"idShort":15,
"labels":[
],

I can get all information in the JSON Array cards (eg "closed", "due",...)

I'm doing for instance,

JSONArray msg2 = (JSONArray) all.get("cards");

then

String boardId = (String) monobjet.get("closed");

and it works fine!

BUT

I don't know how to get "idMembers" ! Any idea, because it's array in a array?

JSONArray msg2 = (JSONArray) all.get("cards");

then

for (int i2 = 0; i2 < size2; i2++) {
                  myobject =  (JSONObject) msg2.get(i2);

                  listTemp2.add(jsonObecjtToMyData(myobject));
              }


String boardName = (String) monobjet.get("name");

For complex json objects such as the one given, I will strongly recommend gson which will do all the task for you.For example:

Gson gson = new GsonBuilder().setPrettyPrinting().create();
Map map = gson.fromJson(inputField.getText(),Map.class);

Now, map conatains all the things you need, so iterate through the map get the idMembers put it in a list and while you are putting it typecast it to string or any datatype that is fit.

You can individually typecast but not an array. So this will compile and run:

public class MainApp {
    public Object obj[]={"foo","loo"};
    public Object obj2 = "soo";
    public static void main(String[] args) {
        MainApp mainApp = new MainApp();
        String name = (String) mainApp.obj2;
        System.out.println(name);
    }
}

Some food for thought:

  1. JSONArray is an object. How would the json handler that you are using would know that it is a JSONArray or list?
  2. Can we do something like this?:

     public class MainApp { public Object obj[]={"foo","loo"}; public static void main(String[] args) { MainApp mainApp = new MainApp(); String name[] = (String[])mainApp.obj; for(String str : name){ System.out.println(str); } }} 

Please use gson and save yourself a lot of pain.Also for complex pojos you can use ObjectMapper .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM