156

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?

2

8 Answers 8

278

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);
Sign up to request clarification or add additional context in comments.

5 Comments

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}]
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.
Use this website to convert your JSON into a Java POJO jsonschema2pojo.org. You can also uncheck getters and setters and use lombok instead to keep POJOs more clear
can you please provide an example for direct conversion to java objects (after what you have already specified in form of annotations)
jsonschema2pojo is also available as a maven plugin.
58

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.

2 Comments

How is for a list?
8
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); 

2 Comments

Kindly add some description to explain the code as well. Thanks!
JsonParser is depricated!
6

In my case, I passed the JSON string as a list. So use the below solution when you pass the list.

ObjectMapper mapper = new ObjectMapper();
String json = "[{\"classifier\":\"M\",\"results\":[{\"opened\":false}]}]";
List<Map<String, Object>> map = mapper
    .readValue(json, new TypeReference<List<Map<String, Object>>>(){});

Comments

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/

Comments

1

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

Comments

0

I have same kind of JSON which is mentioned in the question.

"{
  "Service": "User Service",
  "Work": [
    {
      "Name": "abc",
      "Type": "xyz",
      "Mamber": ["lmn", "jkl"]
    }
  ]
}"

I am using Jackson (objectMapper) to covert the string into Java object.

The readValue using .class type was not working.

readValue("JSON String", Temp.class)

The thing word for me is:

readValue("JSON String", new TypeReference<Map<String, Object>>(){})

Comments

-1
public void parseEmployeeObject() throws NoSuchFieldException, SecurityException, JsonParseException, JsonMappingException, IOException 
  {
   
      Gson gson = new Gson();
      
      ObjectMapper mapper = new ObjectMapper();

        // convert JSON string to Book object
        Object obj = mapper.readValue(Paths.get("src/main/resources/file.json").toFile(), Object.class);
        
        
        endpoint = this.endpointUrl;        

        String jsonInString = new Gson().toJson(obj);
    
      JsonRootPojo organisation = gson.fromJson(jsonInString, JsonRootPojo.class);
      
      
      for(JsonFilter jfil  : organisation.getSchedule().getTradeQuery().getFilter())
      {
         String name = jfil.getName();
         String value = jfil.getValue();
      }
      
      System.out.println(organisation);
      
  }

{
        "schedule": {
        "cron": "30 19 2 MON-FRI",
        "timezone": "Europe/London",        
        "tradeQuery": {
          "filter": [
            {
              "name": "bookType",
              "operand": "equals",
              "value": "FO"
            },
            {
              "name": "bookType",
              "operand": "equals",
              "value": "FO"
            }
          ],
          "parameter": [
            {
              "name": "format",
              "value": "CSV"
            },
            {
              "name": "pagesize",
              "value": "1000"
            }
          ]
        },
        "xslt" :""
        }
      
}


public class JesonSchedulePojo {
    
        public String cron;
        public String timezone;
        public JsonTradeQuery tradeQuery;
        public String xslt;
        
        
        public String getCron() {
            return cron;
        }
        public void setCron(String cron) {
            this.cron = cron;
        }
        public String getTimezone() {
            return timezone;
        }
        public void setTimezone(String timezone) {
            this.timezone = timezone;
        }
    
        public JsonTradeQuery getTradeQuery() {
            return tradeQuery;
        }
        public void setTradeQuery(JsonTradeQuery tradeQuery) {
            this.tradeQuery = tradeQuery;
        }
        public String getXslt() {
            return xslt;
        }
        public void setXslt(String xslt) {
            this.xslt = xslt;
        }
        @Override
        public String toString() {
            return "JesonSchedulePojo [cron=" + cron + ", timezone=" + timezone + ", tradeQuery=" + tradeQuery
                    + ", xslt=" + xslt + "]";
        }
        
        

public class JsonTradeQuery {
    
     public ArrayList<JsonFilter> filter;
        public ArrayList<JsonParameter> parameter;
        public ArrayList<JsonFilter> getFilter() {
            return filter;
        }
        public void setFilter(ArrayList<JsonFilter> filter) {
            this.filter = filter;
        }
        public ArrayList<JsonParameter> getParameter() {
            return parameter;
        }
        public void setParameter(ArrayList<JsonParameter> parameter) {
            this.parameter = parameter;
        }
        @Override
        public String toString() {
            return "JsonTradeQuery [filter=" + filter + ", parameter=" + parameter + "]";
        }
        
        
public class JsonFilter {

    public String name;
    public String operand;
    public String value;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getOperand() {
        return operand;
    }
    public void setOperand(String operand) {
        this.operand = operand;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    @Override
    public String toString() {
        return "JsonFilter [name=" + name + ", operand=" + operand + ", value=" + value + "]";
    }

public class JsonParameter {
    
    public String name;
    public String value;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getValue() {
        return value;
    }
    public void setValue(String value) {
        this.value = value;
    }
    @Override
    public String toString() {
        return "JsonParameter [name=" + name + ", value=" + value + "]";
    }
    
    
public class JsonRootPojo {
    
    public JesonSchedulePojo schedule;

    public JesonSchedulePojo getSchedule() {
        return schedule;
    }

    

    public void setSchedule(JesonSchedulePojo schedule) {
        this.schedule = schedule;
    }



    @Override
    public String toString() {
        return "JsonRootPojo [schedule=" + schedule + "]";
    }

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.