-1

I have a json file with such data:

"records": {
            "abc@zabili.com": {
                "user_id": 523,
                "user_name": "abc",
                "user_email": "abc",
                "time": 10747.5
            },
            "amn@zabili.com": {
                "user_id": 699,
                "user_name": "Amn",
                "user_email": "amn",
                "time": 4439
            },
            "bco@zabili.com": {
                "user_id": 320,
                "user_name": "Bco",
                "user_email": "bco",
                "time": 1927.85
            },
            "bcag@zabili.com": {
                "user_id": 425,
                "user_name": "Bcag",
                "user_email": "bcag",
                "time": 572.8
            },
            "chan@zabili.com": {
                "user_id": 376,
                "user_name": "Chan",
                "user_email": "chan",
                "time": 9769.69
            }
        }

I want to print the user_name and time for each user. How do i do that?

Kaustubh Khare
  • 3,280
  • 2
  • 32
  • 48

4 Answers4

1

Try this:

String jsonData = "Your JSON data here";
JSONArray jsonArray = new JSONArray(jsonData);
for(int i = 0; i < jsonArray.length(); i++) {
    JSONObject jsonObject = jsonArray.getJSONObject(i);

    // get user_id
    String str_user_id = jsonObject.getString("user_id");

    // get user_name
    String str_user_name = jsonObject.getString("user_name");
     //... for other elements
}
CodeMatrix
  • 2,124
  • 1
  • 18
  • 30
Ash
  • 672
  • 6
  • 21
0

String toBeParsed = "String Json";

JSONObject jsonObject = new JSONObject(toBeParsed);

String userObject = jsonObject.optString("records");

JSONArray userDetailsArray = new JSONArray(userObject).length()

for(int i = 0 ; i< userDetailsArray; i++)
{
    JSONObject singleUserObject = userDetailsArray.getJSONObject(i);
    String userName = singleUserObject.getString("user_id");
    String userTime = singleUserObject.getString("user_name");
    // try printing the name & time here
}
Pradeep Kumar
  • 102
  • 1
  • 7
0

Use gson to parse string to HashMap, like this:

Gson gson = new Gson();
HashMap map = gson.fromJson("your-json-str", HashMap.class);
Collection c = map.values();
for(Object o: c){
    map ret = (Map)o;
    String user_id = o.get("user_id");
    ....
}
sven
  • 86
  • 6
0

As @Kaustubh Khare say, use jackson

ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.readTree(jsonStr);//jsonStr is your json str
JsonNode records = jsonNode.get("records");
Iterator<JsonNode> elements = records.elements();
while (elements.hasNext()) {
    JsonNode next = elements.next();
    System.out.println(next.get("user_name"));
    System.out.println(next.get("time"));
}
dai
  • 1,025
  • 2
  • 13
  • 33