Check if a particular JSON Object is available or not

前端 未结 3 2162
太阳男子
太阳男子 2021-02-13 04:38

I have JSON File as below which has to be dumped into an ArrayList:

{
 \"main1\" : [
  {
     \"child1\" : valueA,
     \"child2\" : valueB,
     \"child3\" : va         


        
相关标签:
3条回答
  • 2021-02-13 05:12
    getJSONObject("child2");
    

    Will throw an exception if child2 does not exist. Try this instead:

    getchild2 = jArray.getJSONObject(j).optJSONObject("child2");
    

    That way you don't have to catch an exception if child2 doesn't exist and can instead check for null.

    0 讨论(0)
  • 2021-02-13 05:16

    Anyway, I got the solution with some Googling: I re-framed it as,

     if (!jArray.getJSONObject(j).has("child2")) {
      map.put("Second Value", "N.A");
     } else {
      map.put("Second Value", jArray.getJSONObject(j).getString("child2"));
     }
    

    Creating the JSONObject getchild2 = jArray.getJSONObject(j).getJSONObject("child2"); was rather, unnecessary.

    And this works, rather perfectly! Refer this for more details: Checking if exists subObject in JSON

    Thanks everyone for the help!

    0 讨论(0)
  • 2021-02-13 05:32

    Try this:

    {"main1" : [{
                 "id":"1"
                   "child1" : "valueA",
                   "child2" : "valueB",
                   "child3" : "valueC",
                }, {
                    "id":"2"
                      "child1" : "value1",
                     "child3"  : "value3",
               }]
    }
    
    0 讨论(0)
提交回复
热议问题