141

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
  • 3,444
  • 6
  • 32
  • 59
Rolando
  • 58,640
  • 98
  • 266
  • 407
  • 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

7 Answers7

257

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
  • 113,358
  • 34
  • 211
  • 239
  • 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
  • jsonschema2pojo is also available as a maven plugin. – julaine Nov 11 '22 at 09:28
51

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,297
  • 1
  • 21
  • 27
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); 
Praveen Kokkula
  • 260
  • 1
  • 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/

3

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>>>(){});
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
Sathiamoorthy
  • 8,831
  • 9
  • 65
  • 77
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
Valentyn Kolesnikov
  • 2,029
  • 1
  • 24
  • 31
-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 + "]";
    }
Procrastinator
  • 2,526
  • 30
  • 27
  • 36