0

I have got the following Map Structure

{CDetails=[{"collegeName":"Peters Stanford","collegeLoc":"UK"},{}]}

I am trying to get the collegeLoc value from the above mentioned structure

This is what i tried

public static void main(String[] args) {
     Map < String, Object > empMap = new HashMap < > ();

    JSONObject collegeNameJsonObj = new JSONObject();
    collegeNameJsonObj.put("collegeName", "Peters Stanford");

    JSONObject collegeIdJsonObj = new JSONObject();
    collegeNameJsonObj.put("collegeLoc", "UK");

    JSONArray jsonArray = new JSONArray();
    jsonArray.add(collegeNameJsonObj);
    jsonArray.add(collegeIdJsonObj);

    empMap.put("CDetails", jsonArray);


  System.out.println(empMap.entrySet().stream().filter(map->map.getKey().equals("CDetails")).map(map->map.getValue()).collect(Collectors.toList()));

Struck here , unable to loop / parse further .

how to get the collegeLoc value in this case ? any help would be great .

1
  • Can you get value from JSONObject by key,like jsonObject.getAsString(key)? Commented May 5, 2020 at 3:04

3 Answers 3

1

Try the following code,

empMap
    .entrySet()
    .stream()
    .filter(map -> map.getKey().equals("CDetails"))
    .forEach(e -> {
            JSONArray jsArray = (JSONArray) e.getValue();
            for (Object jsObject : jsArray) {
                JSONObject obj = (JSONObject) jsObject;
                if (obj.containsKey("collegeLoc")) {
                    System.out.println(obj.getAsString("collegeLoc"));
                }
            }
    });
Sign up to request clarification or add additional context in comments.

Comments

0

It might be

json.getJSONArray("CDetails").getJSONObject(0).getString("slogan")

Or, which is better, create a Value Object and serialize / deserialize it. It will be much easier to manipulate & navigate with Java class rather than with a pure JSON document.

class ValueObject {
  @JsonProperty("CDetails")
  private List<Detail> details;

  static class Detail {
    private String collegeName;
    private String collegeLoc;
  }
}

Comments

0

If use net.minidev.json json lib,try the follow code:

JSONArray array = (JSONArray) empMap.get("CDetails");

array.stream().filter(o -> {
    JSONObject jsonObject = (JSONObject) o;
    return jsonObject.containsKey("collegeLoc");
}).map(o -> {
    JSONObject jsonObject = (JSONObject) o;
    return jsonObject.getAsString("collegeLoc");
}).forEach(System.out::println);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.