简体   繁体   中英

json parsing using JSONObject

My data is like this:

   {
       "region":  
             ["{'price':'119','volume':'20000','pe':'0','eps':'4.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'}",   
              "{'price':'112','volume':'20000','pe':'0','eps':'9.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'}",   
              "{'price':'118','volume':'20000','pe':'0','eps':'1.22','week53low':'92','week53high':'134.4','daylow':'117.2','dayhigh':'119.2','movingav50day':'115','marketcap':'0','time':'2015-11-25 05:13:34.996'}"  
              ]  
    }  

I am doing like below;

        JSONObject jsonObj = new JSONObject(jsonString);
        JSONArray regionArray = jsonObj.getJSONArray("region");  

How do I get each price..

for (int i = 0; i < regionArray.length(); i++) {

             JSONObject item = regionArray.getJSONObject(i); 
             System.out.println(item.getString("price"));
        }  

Caused by: com.gemstone.org.json.JSONException: JSONArray[0] is not a JSONObject.

You have an array of Strings, not of JSON objects, so you can't do JSON object methods on it.

In order for your code to work, your JSON would have to look like this:

{
  "region": [
    {
      "price": "119",
      "volume": "20000",
      "pe": "0",
      "eps": "4.22",
      "week53low": "92",
      "week53high": "134.4",
      "daylow": "117.2",
      "dayhigh": "119.2",
      "movingav50day": "115",
      "marketcap": "0",
      "time": "2015-11-25 05:13:34.996"
    },
    {
      "price": "112",
      "volume": "20000",
      "pe": "0",
      "eps": "9.22",
      "week53low": "92",
      "week53high": "134.4",
      "daylow": "117.2",
      "dayhigh": "119.2",
      "movingav50day": "115",
      "marketcap": "0",
      "time": "2015-11-25 05:13:34.996"
    },
    {
      "price": "118",
      "volume": "20000",
      "pe": "0",
      "eps": "1.22",
      "week53low": "92",
      "week53high": "134.4",
      "daylow": "117.2",
      "dayhigh": "119.2",
      "movingav50day": "115",
      "marketcap": "0",
      "time": "2015-11-25 05:13:34.996"
    }
  ]
}

I just replaced that automatically in a text editor. You can actually let the numbers out of their "" enclosure if you want.

Have a look at it here: http://www.jsoneditoronline.org/

And here's some info on Json: http://www.json.org/

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