0

I have a json document with multiple objects. I have managed to print this out as a map but I want to be able to access elements within the values.

I can print the Map, but want to be able to print specific elements within the keys

for (Map.Entry<String,Object> entry : myMap.entrySet()) {
        System.out.println("Key: "+entry.getKey() + " Value: "+entry.getValue());
    }

This outputs the following:

Key: header1 Value: {id=123456, contents=[cat,dog,hamster]}
Key: header2 Value: {id=234567, contents=[spoon,knife,fork]}

I would like to be able to loop through and on each iteration assign id to a string and contents to a list

3
  • 1
    What have you tried so far. Sounds like homework and is too broad. Commented Jan 24, 2019 at 9:42
  • Sadly I am a bit old for homework! My issue is I'm not really sure if what I'm asking is possible with the data structure without using a split or something equally bodged! I am trying to access with something like myMap.get("contents") but this doesn't work and I'm not really sure what sort of thing I should be looking up with regards to the syntax Commented Jan 24, 2019 at 10:07
  • 1
    @NicholasK looks like someone has done his homework. :) Commented Jan 24, 2019 at 10:17

2 Answers 2

1

The easiest solution is to make a Class, which represents the JSON. For you, it will be like this:

public class Contents {
    private int id;
    private List<String> contents;

    //No arguments constructor, getters and setters for every field
    //You can make with @JsonCreator, too. Read Jackson documentation
};

Then you just read it as object using Jackson's ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
Contents result = mapper.readValue(entry.getValue(), Contents.class);

After, this you can do whatever you like with the object. Later, you can even write it to File/Stream etc.

Sign up to request clarification or add additional context in comments.

Comments

0

I had a couple of issues with code I had assume to be working but have solved this now with a little help from a colleague.

value.getContents();

Was the thing I was looking for!

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.