0

currently an facing a problem how to de serialize list of objects in json format to pojo. in my works using jersey rest service it can consume json. how can de-serialize rest request with json object having array of objects .

json array

{
    "subject": "hi",
    "description": [
        {
            "subject": "hi"
        },
        {
            "subject": "hi"
        }
    ]
}

my pojo class

public class t {

    private String subject;
    private List<t2> description;

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public List<t2> getDescription() {
        return description;
    }

    public void setDescription(List<t2> description) {
        this.description = description;
    }

}

t2.class

public class t2 {
    private String subject;

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }
}
Midhun Pottammal
  • 1,107
  • 1
  • 11
  • 25
  • So do you just want to convert a json string to java object? – Amir Jun 19 '15 at 09:28
  • I think you can find the solution in this similar question: http://stackoverflow.com/questions/11106379/how-to-deserialize-json-array – Amir Jun 19 '15 at 09:31
  • What is the actual problem here? That type and JSON seem compatible so you just declare that resource method takes one parameter of type `t` and that's it. – StaxMan Jun 19 '15 at 22:37

1 Answers1

-1

Use TypeReference. Eg:

import java.io.IOException;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;


public class JacksonParser {

    public static void main(String[] args) {
        t data = null;
        String json = "{\"subject\":\"hi\",\"description\":[{\"subject\":\"hi\"},{\"subject\":\"hi\"}]}";
        ObjectMapper mapper = new ObjectMapper();
        try {
            data = mapper.readValue(json, new TypeReference<t>() { });
        } catch (JsonParseException e) {
            System.out.println(e.getMessage());
        } catch (JsonMappingException e) {
            System.out.println(e.getMessage());
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        System.out.println(data);
    }

}
Syam S
  • 8,421
  • 1
  • 26
  • 36
  • 1
    You don't need to use `TypeReference` there because `t` is not generic. You can just use `t.class instead. –  Jun 19 '15 at 09:51