Android create a JSON array of JSON Objects

后端 未结 4 485
一整个雨季
一整个雨季 2021-01-07 08:46

hi does anyone know how to create a Array that contains objects that in each objects contain several objects? i just can\'t seem to get my head round it

the structur

相关标签:
4条回答
  • 2021-01-07 08:51

    What I would suggest to do is to use JackSON JSON Parser library http://jackson.codehaus.org/ Then you can create a Class with the same fields as the JSON son the mapping from JSON To class will be direct. So once you have all the items from JSON into a List of class you can order by dates or manipulate data as you want. Imagine that src is a String containing the JSON text. With JackSON lib you just need to do this.

    ObjectMapper mapper = new ObjectMapper();

    List<Fixture> result = mapper.readValue(src, new TypeReference<List<Fixture>>() { });

    0 讨论(0)
  • 2021-01-07 09:01

    Here are two pieces of JSON which fit your description which is "Array that contains objects that in each objects contain several objects". The first method uses Arrays inside Objects. The other one uses Objects in Objects.

    Method 1

    [ { "name" : "first object in array" , "inner array" : [ { <object> } , { <object> } ] }
     , { "name" : "second object in array" , "inner array" : [ { <object> } , { <object> } ] } ]
    

    To parse the above you need two nested for loops (or something recursive).

    Method 2

    [ { "name" : "first object in array" , "first inner object" : { <object> } , "second inner object" : { <object> } } , <etc.> ] } ]
    

    The second method can be parsed with a single for loop because you know in advance the number of inner objects to expect.

    0 讨论(0)
  • 2021-01-07 09:07

    Do you mean that?:

    JSONObject obj = new JSONObject();
    obj.put("x", "1");
    JSONObject parent_object = new JSONObject();
    parent_object.put("child", obj);
    JSONArray array = new JSONArray(parent_object.toString());
    
    0 讨论(0)
  • 2021-01-07 09:09

    JSON String

    {
    "result": "success",
    "countryCodeList":
    [
      {"countryCode":"00","countryName":"World Wide"},
      {"countryCode":"kr","countryName":"Korea"}
    ] 
    }
    

    Here below I am fetching country details

    JSONObject json = new JSONObject(jsonstring);
    JSONArray nameArray = json.names();
    JSONArray valArray = json.toJSONArray(nameArray);
    
    JSONArray valArray1 = valArray.getJSONArray(1);
    
    valArray1.toString().replace("[", "");
    valArray1.toString().replace("]", "");
    
    int len = valArray1.length();
    
    for (int i = 0; i < valArray1.length(); i++) {
    
     Country country = new Country();
     JSONObject arr = valArray1.getJSONObject(i);
     country.setCountryCode(arr.getString("countryCode"));                        
     country.setCountryName(arr.getString("countryName"));
     arrCountries.add(country);
    }
    
    0 讨论(0)
提交回复
热议问题