How to convert the following JSON String to POJO

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

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

Tags:

Java

Json

Jackson