20

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

{
  "user": {
    "0": {
      "firstName": "Monica",
      "lastName": "Belluci"
    },
    "1": {
      "firstName": "John",
      "lastName": "Smith"
    },
    "2": {
      "firstName": "Owen",
      "lastName": "Hargreaves"
    }
  }
}

To convert this to Java object I've created the following classes:

class User {
    private Map<String, MyObject> user = new HashMap<>();
    //Getter and Setter is here
}

class MyObject {
    private String firstName;
    private String lastName;
    //Getters and Setters are here
}

I'm using Jackson library to convert JSON to Java. Here is how I'm using the Jackson for conversion:

ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(jsonString, User.class);

The problem is that with this conversion above the Map inside the User object is always empty. What am I doing wrong?

Thanks in advance.

Arsen Davtyan
  • 1,891
  • 8
  • 23
  • 40

4 Answers4

24

I think it should work. I've executed this code and it works fine. Here is my example.

import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;

public class TestJackson {

public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        String testJson = "{\n" + "  \"user\": {\n" + "    \"0\": {\n" + "      \"firstName\": \"Monica\",\n" + "      \"lastName\": \"Belluci\"\n" + "    },\n" + "    \"1\": {\n" + "      \"firstName\": \"John\",\n" + "      \"lastName\": \"Smith\"\n" + "    },\n" + "    \"2\": {\n" + "      \"firstName\": \"Owen\",\n" + "      \"lastName\": \"Hargreaves\"\n" + "    }\n" + "  }\n" + "}";
        User readValue = mapper.readValue(testJson, User.class);
        System.out.println("readValue = " + readValue);
    }
}

and the User.class:

import java.util.HashMap;
import java.util.Map;

class User {
    private Map<String, MyObject> user = new HashMap<String, MyObject>();

    public Map<String, MyObject> getUser() {
        return user;
    }

    public void setUser(Map<String, MyObject> user) {
        this.user = user;
    }

    @Override
    public String toString() {
        return "User{" +
                "user=" + user +
                '}';
    }
}

class MyObject {
    private String firstName;
    private String lastName;

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    @Override
    public String toString() {
        return "MyObject{" +
                "firstName='" + firstName + '\'' +
                ", lastName='" + lastName + '\'' +
                '}';
    }
}
K. Gol
  • 1,391
  • 12
  • 15
  • Getter and Setter of pojo is must – ketankk Dec 27 '17 at 06:59
  • If you do any custom "renaming" with Pojo properites to json element names (using import com.fasterxml.jackson.annotation.JsonProperty;) then the library that you use for annotations (import com.fasterxml.jackson.annotation.JsonProperty;) has to be consistent with the serializer/deserializer) (com.fasterxml.jackson.databind.ObjectMapper;) Aka, you cannot have jackson annotations and then use Gson to serializer/deserialize for example. – granadaCoder Sep 29 '20 at 17:38
  • Jackson marshalling/unmarshalling requires following jar files of same version. (1) jackson-core, (2) jackson-databind, (3) jackson-annotations – Uvuvwevwevwe Feb 24 '21 at 08:04
9

Use can done with the help of gson library.

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonToJava {

    public static void main(String[] args) throws IOException {
        try(Reader reader = new InputStreamReader(JsonToJava.class.getResourceAsStream("/Server2.json"), "UTF-8")){
            Gson gson = new GsonBuilder().create();
            Person p = gson.fromJson(reader, YourPOJOClass.class);
            System.out.println(p);
        }
    }
}

visit this link hope this helps :)

Pratik Gondil
  • 689
  • 1
  • 6
  • 17
2

I had one additional issue, that i faced when converting JSON to Java POJO: com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of class out of START_ARRAY token ...

If anyone faces this issue, this is because JSON is expecting an object {} but it sees an array [{}] within the JSON String that is passed in

ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(jsonString, User.class);

To fix

User[] user = mapper.readValue(jsonString, User[].class);

Reference: https://stackoverflow.com/a/33515796/4167786

she12
  • 91
  • 4
1

You can try below code, It works fine..

public class User {

    private Map<String, Map<String, String>> user;

    public Map<String, Map<String, String>> getUser() {
        return user;
    }

    public void setUser(Map<String, Map<String, String>> user) {
        this.user = user;
    }

}


public class JsonCast {

    public static void main(String args[]) {

        String response = "{\"user\" : {\"0\": {\"firstName\": \"Monica\",\"lastName\": \"Belluci\"},\"1\": { \"firstName\": \"John\",\"lastName\": \"Smith\"}}}";

        ObjectMapper mapper = new ObjectMapper();
        try {

            User user = mapper.readValue(response, User.class);

            System.out.println(user.getUser().get("0"));

        } catch (IOException e) {

            e.printStackTrace();
        }
    }

}
Arsen Davtyan
  • 1,891
  • 8
  • 23
  • 40
lahirumw
  • 153
  • 1
  • 1
  • 9