0

So, this is the json String that I've.

String json ="{\"BPDataList\":[{\"BPL\":5,\"DataID\":\"6deacbc373e74e1794a7*****\",\"HP\":124,\"HR\":82,\"IsArr\":-1,\"LP\":82,\"Lat\":-1,\"Lon\":-1,\"MDate\":1373392309,\"Note\":\"\",\"LastChangeTime\":1373362486,\"DataSource\":\"FromDevice\",\"TimeZone\":\"+0800\"}],\"BPUnit\":0,\"CurrentRecordCount\":50,\"NextPageUrl\":\"https%3a%2f%2fapi.ihealthlabs.com%3a8443%2fopenapiv2%2fuser%2f05dffbe0dd*****%2fbp.json%2f%3fclient_id%3dddb9cbc759*****%26client_secret%3d4738f9d00e*****%26redirect_uri%3dhttp%253a%252f%252fapi.testweb2.com%252foauthtest.aspx%26access_token%3dxpoBt0ThQQ*****%26start_time%3d1342007016%26end_time%3d1405079016%26page_index%3d2%26sc%3dd63493704c*****%26sv%3d113cb40956*****\",\"PageLength\":50,\"PageNumber\":1,\"PrevPageUrl\":\"\",\"RecordCount\":335}";

I'm using this code to store it into a map;

Map<String, Object> map = new HashMap<String, Object>();
JSONObject jObject = new JSONObject(json);

Iterator<?> keys = jObject.keys();
while (keys.hasNext()) {
    try {
        String key = (String) keys.next();
        Object value = jObject.getJSONArray(key);
        log.debug("value--" + map);
        map.put(key, value);
    } catch (Exception e) {
        log.trace("getUserBG--", e);
    }
}

But, it's storing only the first element into the map i.e. BPDataList. What am i doing wrong here?

this is the content of the map, when I print it.

map:{BPDataList=[{"DataSource":"FromDevice","IsArr":-1,"DataID":"6deacbc373e74e1794a7*****","BPL":5,"HR":82,"MDate":1373392309,"Lat":-1,"Note":"","HP":124,"TimeZone":"+0800","Lon":-1,"LastChangeTime":1373362486,"LP":82}]}

json

{
  "BPDataList": [
    {
      "BPL": 5,
      "DataID": "6deacbc373e74e1794a7*****",
      "HP": 124,
      "HR": 82,
      "IsArr": -1,
      "LP": 82,
      "Lat": -1,
      "Lon": -1,
      "MDate": 1373392309,
      "Note": "",
      "LastChangeTime": 1373362486,
      "DataSource": "FromDevice",
      "TimeZone": "+0800"
    }
  ],
  "BPUnit": 0,
  "CurrentRecordCount": 50,
  "NextPageUrl": "abc",
  "PageLength": 50,
  "PageNumber": 1,
  "PrevPageUrl": "",
  "RecordCount": 335
}
Drunken Daddy
  • 7,326
  • 14
  • 70
  • 104

1 Answers1

1

This is because everything except BPDataList isn't a JSONArray.

Change your code to

while (keys.hasNext()) {
    try {
        String key = (String) keys.next();
        Object value = jObject.get(key);
        log.debug("value--" + map);
        map.put(key, value);
    } catch (Exception e) {
        log.trace("getUserBG--", e);
    }
}

This should work fine

ThomasS
  • 705
  • 1
  • 11
  • 30
  • Thank you. It worked. but I wonder why it didn't throw any exception – Drunken Daddy Aug 16 '15 at 12:47
  • I don't know in what IDE you are working but in mine (Eclipse) it did throw exceptions. They should be inside your log due to the try-catch. Personally I advise against using catch(Exception e), certainly while still developing. – ThomasS Aug 16 '15 at 12:50