How to check whether the given object is object or Array in JSON string

后端 未结 4 1783
不思量自难忘°
不思量自难忘° 2020-12-05 08:04

I am getting JSON string from website. I have data which looks like this (JSON Array)

 myconf= {URL:[blah,blah]}

but some times this data c

4条回答
  •  甜味超标
    2020-12-05 08:57

    I was also having the same problem. Though, I've fixed in an easy way.

    My json was like below:

    [{"id":5,"excerpt":"excerpt here"}, {"id":6,"excerpt":"another excerpt"}]
    

    Sometimes, I got response like:

    {"id":7, "excerpt":"excerpt here"}
    

    I was also getting error like you. First I had to be sure if it's JSONObject or JSONArray.

    JSON arrays are covered by [] and objects are with {}

    So, I've added this code

    if (response.startsWith("[")) {
      //JSON Array
    } else {
      //JSON Object 
    }
    

    That worked for me and I wish it'll be also helpful for you because it's just an easy method

    See more about String.startsWith here - https://www.w3schools.com/java/ref_string_startswith.asp

提交回复
热议问题