Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert the following json string to java object?

Tags:

java

json

jackson

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?

like image 884
Rolando Avatar asked Apr 25 '12 02:04

Rolando


People also ask

How do you convert JSON to Java object?

We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.

How can I convert JSON to object?

Use the JavaScript function JSON. parse() to convert text into a JavaScript object: const obj = JSON.


2 Answers

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); 
like image 185
StaxMan Avatar answered Oct 07 '22 00:10

StaxMan


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.

like image 21
jpalm Avatar answered Oct 07 '22 00:10

jpalm