111

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?

SSK
  • 2,800
  • 6
  • 26
  • 49
Rolando
  • 51,528
  • 92
  • 250
  • 377
  • possible duplicate of [Convert a JSON string to object in Java?](http://stackoverflow.com/questions/1395551/convert-a-json-string-to-object-in-java) – bummi Feb 10 '15 at 23:07
  • To get the POJO of the Json String - https://json2csharp.com/json-to-pojo – rakesh sinha Apr 28 '21 at 23:13

5 Answers5

208

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);
StaxMan
  • 108,392
  • 32
  • 202
  • 235
  • I tried to send this type of json string with jackson but it returns only null values,`[{"id":62,"name":"projectname1","batchClassId":1283,"batchClassName":"sample_batchclass26","assetCount":0},{"id":8,"name":"projectname_tmp","batchClassId":1283,"batchClassName":"sample_batchclass26","assetCount":0}]` – Madura Harshana Jul 19 '13 at 05:41
  • That is a JSON Array, so it must be bound to Java `Collection` (like `List`) or array (can use type `Object[].class`). Or just to `java.lang.Object` (will be of type `List`). It will work just fine. – StaxMan Jul 19 '13 at 20:21
  • 1
    Use this website to convert your JSON into a Java POJO http://www.jsonschema2pojo.org/. You can also uncheck getters and setters and use lombok instead to keep POJOs more clear – jellyDean Sep 20 '17 at 14:23
  • can you please provide an example for direct conversion to java objects (after what you have already specified in form of annotations) – Dhruv Singhal Aug 17 '18 at 11:16
39

Check out Google's Gson: http://code.google.com/p/google-gson/

From their website:

Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

You would just need to make a MyType class (renamed, of course) with all the fields in the json string. It might get a little more complicated when you're doing the arrays, if you prefer to do all of the parsing manually (also pretty easy) check out http://www.json.org/ and download the Java source for the Json parser objects.

jpalm
  • 2,107
  • 1
  • 20
  • 26
9
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject object = (JsonObject) parser.parse(response);// response will be the json String
YourPojo emp = gson.fromJson(object, YourPojo.class); 
Praveen Kokkula
  • 242
  • 3
  • 11
3

Gson is also good for it: http://code.google.com/p/google-gson/

" Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object. Gson can work with arbitrary Java objects including pre-existing objects that you do not have source-code of. "

Check the API examples: https://sites.google.com/site/gson/gson-user-guide#TOC-Overview More examples: http://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/

0

Underscore-java (which I am the developer of) can convert json to Object.

import com.github.underscore.U;

    String jsonString = "{\n" +
            "        \"libraryname\":\"My Library\",\n" +
            "                \"mymusic\":[{\"Artist Name\":\"Aaron\",\"Song Name\":\"Beautiful\"},\n" +
            "        {\"Artist Name\":\"Britney\",\"Song Name\":\"Oops I did It Again\"},\n" +
            "        {\"Artist Name\":\"Britney\",\"Song Name\":\"Stronger\"}]}";
    Map<String, Object> jsonObject = U.fromJsonMap(jsonString);
    System.out.println(jsonObject);

    // {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}]}

    System.out.println(U.<String>get(jsonObject, "mymusic[0].Artist Name"));
    // Aaron
Valentyn Kolesnikov
  • 1,840
  • 1
  • 21
  • 28