Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting JSON array to POJO using jackson object mapper

This is possibly a duplicate question.. please refer this link.
I am able to map one json object to POJO.But how can i convert array of json object to pojo using the same jackson framework.

private void jsonToPojo(){
   ObjectMapper mapper=new ObjectMapper();

    try {
        User1 user1=mapper.readValue(readFromFile(), User1.class);
        User1[] user2=mapper.readValue(readFromFile(), User1[].class);
        System.out.println(user1);
        Toast.makeText(getApplicationContext(), "inside try", 0).show();
    } catch (JsonParseException e) {
        // TODO Auto-generated catch block
        Log.i("Exception", "jsonparseexception");
        e.printStackTrace();
    } catch (JsonMappingException e) {
        // TODO Auto-generated catch block
        Log.i("Exception", "jsonmapping exception");
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        Log.i("Exception", "ioexception");
        e.printStackTrace();
    }
}

This is the class user object.

public class User {
private int age = 23;
private String name = "amal";
private List<String> messages = new ArrayList<String>() {
    {
        add("hi");
        add("how");
        add("are u.");
    }
};

//getter and setter methods

@Override
public String toString() {
    return "User [age=" + age + ", name=" + name + ", " +
            "messages=" + messages + "]";
}

This is what i tried to do:(readFromFile() takes json from a file)

User1[] user2=mapper.readValue(readFromFile(), User1[].class);

The jsonToPojo() is working well for only one object. However, if i try the above line of code,its not taking the following json:

[ 
 {
   "age":"23",
   "messages":["hi","how","are u."],
   "name":"amal"
 },

 {
   "age":"98",
   "messages":["Reply","my","question"],
   "name":"You"
 }
]
like image 240
amalBit Avatar asked May 11 '13 12:05

amalBit


People also ask

How do you convert JSON to Java object?

We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String.

What is the use of Jackson ObjectMapper?

ObjectMapper is the main actor class of Jackson library. ObjectMapper class ObjectMapper provides functionality for reading and writing JSON, either to and from basic POJOs (Plain Old Java Objects), or to and from a general-purpose JSON Tree Model (JsonNode), as well as related functionality for performing conversions.

What is the use of ObjectMapper readValue?

The simple readValue API of the ObjectMapper is a good entry point. We can use it to parse or deserialize JSON content into a Java object. Also, on the writing side, we can use the writeValue API to serialize any Java object as JSON output.


1 Answers

Try something like this:

public class Test {

/**
 * @param args
 */
public static void main(String[] args) {
    User a = new User(23, "amal");
    ArrayList<String> message = new ArrayList<String>();
    message.add("m1");
    message.add("m2");
    a.setMessages(message);

    User b = new User(58, "pete");
    User[] ab = new User[] {a, b};

    ObjectMapper mapper = new ObjectMapper();

    try {
        String s1 = getJson1(a);
        System.out.println(s1);
        User user1 = mapper.readValue(s1, User.class);
        System.out.println(user1);

        System.out.println("----------------");

        String s2 = getJson2(ab);
        System.out.println(s2);
        User[] user2 = mapper.readValue(s2, User[].class);
        for (User u : user2)
            System.out.println(u);

    } catch (Exception e) {
        e.printStackTrace();
    }

}

    private static String getJson1(User user) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(user);
    }

    private static String getJson2(User[] ab) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(ab);
    }

}

public class User {
    private int               age;
    private String            name;
    private ArrayList<String> messages;

    public User() {
        super();
    }

    public User(int age, String name) {
        this();
        this.age = age;
        this.name = name;
    }

    // ****************
    // Getter & Setter ....
    // ****************
}

You will get this Output:

{"age":23,"name":"amal","messages":["m1","m2"]}
User [age=23, name=amal, messages=[m1, m2]]
----------------
[{"age":23,"name":"amal","messages":["m1","m2"]},{"age":58,"name":"pete","messages":null}]
User [age=23, name=amal, messages=[m1, m2]]
User [age=58, name=pete, messages=null]
like image 113
DennisH Avatar answered Oct 23 '22 01:10

DennisH