Arsen Davtyan
Arsen Davtyan

Reputation: 1957

How to convert the following JSON String to POJO

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.

Upvotes: 23

Views: 140485

Answers (5)

MJay
MJay

Reputation: 1058

Try pasting your json string to this link, it will do the rest, writing the required classes.

Upvotes: 0

she12
she12

Reputation: 111

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

Upvotes: 3

lahirumw
lahirumw

Reputation: 183

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();
        }
    }

}

Upvotes: 1

Pratik Gondil
Pratik Gondil

Reputation: 699

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 :)

Upvotes: 9

K. Gol
K. Gol

Reputation: 1616

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 + '\'' +
                '}';
    }
}

Upvotes: 27

Related Questions