Search code examples
javajsonjackson

How to convert the following json string to java object?


I want to convert the following JSON string to a java object:

String jsonString = "{
  "libraryname": "My Library",
  "mymusic": [
    {
      "Artist Name": "Aaron",
      "Song Name": "Beautiful"
    },
    {
      "Artist Name": "Britney",
      "Song Name": "Oops I did It Again"
    },
    {
      "Artist Name": "Britney",
      "Song Name": "Stronger"
    }
  ]
}"

My goal is to access it easily something like:

(e.g. MyJsonObject myobj = new MyJsonObject(jsonString)
myobj.mymusic[0].id would give me the ID, myobj.libraryname gives me "My Library").

I've heard of Jackson, but I am unsure how to use it to fit the json string I have since its not just key value pairs due to the "mymusic" list involved. How can I accomplish this with Jackson or is there some easier way I can accomplish this if Jackson is not the best for this?


Solution

  • No need to go with GSON for this; Jackson can do either plain Maps/Lists:

    ObjectMapper mapper = new ObjectMapper();
    Map<String,Object> map = mapper.readValue(json, Map.class);
    

    or more convenient JSON Tree:

    JsonNode rootNode = mapper.readTree(json);
    

    By the way, there is no reason why you could not actually create Java classes and do it (IMO) more conveniently:

    public class Library {
      @JsonProperty("libraryname")
      public String name;
    
      @JsonProperty("mymusic")
      public List<Song> songs;
    }
    public class Song {
      @JsonProperty("Artist Name") public String artistName;
      @JsonProperty("Song Name") public String songName;
    }
    
    Library lib = mapper.readValue(jsonString, Library.class);