sareem
sareem

Reputation: 429

Jackson to parse complex objects

I want to parse json object using jackson. My object structure is something like: LiveShow.java:

@JsonIgnoreProperties(ignoreUnknown = true)
public class LiveShow implements Serializable{

    @JsonProperty("showid")
    public String showid;
    @JsonProperty("time")
    public String time;
    @JsonProperty("provider")
    public int provider;
    @JsonProperty("sponser")
    public String sponser;


    @JsonCreator
    public LiveShow(@JsonProperty("showid") String showid, 
            @JsonProperty("time") String time,
            @JsonProperty("provider") int provider,
            @JsonProperty("sponser") String sponser) {
        super();
        this.showid= showid;
        this.time = time;
        this.provider = provider;
        this.sponser = sponser;
    } 

    public String getShowid() {
        return showid;
    }

    public void setTopid(String showid) {
        this.showid = showid;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public int getProvider() {
        return provider;
    }

    public void setProvider(int provider) {
        this.provider = provider;
    }

    public String getSponser() {
        return sponser;
    }

    public void setSponser(String sponser) {
        this.sponser = sponser;
    }
}

MonthlyShows.java:

@JsonIgnoreProperties(ignoreUnknown = true)
//@JsonInclude(Include.NON_NULL)
public class MonthlyShows implements Serializable{
    @JsonProperty("live_shows")
    public LiveShow[] live_shows;
    @JsonProperty("month")
    public String month;
    @JsonCreator
    public MonthlyShows(@JsonProperty("live_shows") LiveShow[] live_shows, 
            @JsonProperty("month") String month) {
        super();
        setLive_shows(live_shows);
        setMonth(month);
    }

    public LiveShow[] getLive_shows() {
        return live_shows;
    }

    public void setLive_shows(LiveShow[] live_shows) {
        try{
            this.live_shows = new LiveShow[live_shows.length];
            for (int i = 0; i < live_shows.length; i++)
                this.live_shows[i] = live_shows[i];
            }catch(Exception e){

                System.err.println("live_shows is null");
                e.printStackTrace();
            }
    }

    public String getMonth() {
        return month;
    }

    public void setMonth(String month) {
        this.month = month;
    }
}

How I parse the object:

ObjectMapper mapper = new ObjectMapper();
MonthlyShows showsInApril = mapper.readValue(jsonString, TypeFactory.defaultInstance().constructType(MonthlyShows.class));
System.out.println("month:" + showsInApril.month);
for(LiveShow s : showsInApril.live_shows)
    System.out.println(s.showid+ "\t" + s.time + "\t" + s.provider);

I'm getting null pointer exception which I understood to mean that I can't parse such compound/complex object.

java.lang.NullPointerException
    at MonthlyShows.setLive_shows(MonthlyShows.java:49)
    at MonthlyShows.<init>(LiveRelevanceJudgments.java:25)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.fasterxml.jackson.databind.introspect.AnnotatedConstructor.call(AnnotatedConstructor.java:114)
    at com.fasterxml.jackson.databind.deser.std.StdValueInstantiator.createFromObjectWith(StdValueInstantiator.java:256)
    at com.fasterxml.jackson.databind.deser.impl.PropertyBasedCreator.build(PropertyBasedCreator.java:135)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeUsingPropertyBased(BeanDeserializer.java:444)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1123)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:298)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:133)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3789)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2817)
    at Test.main(Test.java:189)

month: April

Is there a way to work around the problem?

EDIT:

example of json object I'm parsing is:

{
    "live_shows":[
        {"showid":"show1","time":"02216629","provider":0,"sponser":"governmental"},
        {"showid":"show2","time":"00050340","provider":2,"sponser":"business"}
    ],
    "month":"April"
}

And I fixed the types of attributes as pointed by Nico in the comments below. + provided the full classes as requested

Upvotes: 1

Views: 6244

Answers (2)

Francesco
Francesco

Reputation: 1792

You can use @JsonInclude(Include.NON_NULL) to avoid deserialization of null attributes:

@JsonInclude(Include.NON_NULL)
public class MonthlyShows {

  @JsonProperty("live_shows")
  public LiveShow[] live_shows;
  ...
}

and change your MonthlyShows constructor this way:

@JsonCreator
public MonthlyShows(@JsonProperty("live_shows") LiveShow[] live_shows, 
@JsonProperty("month") String month) {
  super();
  this.live_shows = live_shows;
  this.month = month;
}

Here is full code sample:

public class DeserializationTests {

private ObjectMapper mapper;

@Before
public void setUp() {
mapper = new ObjectMapper();
}

@Test
public void deserializeFullMonthlyShows() throws Exception {
String jsonString = "{\"live_shows\":[{\"showid\":\"showid1\",\"time\":14000000000,\"provider\":1,\"sponser\":\"sponser1\"},{\"showid\":\"showid2\",\"time\":15000000000,\"provider\":2,\"sponser\":\"sponser2\"}],\"month\": \"April\"}";
MonthlyShows showsInApril = mapper.readValue(jsonString, MonthlyShows.class);
printOutMonthlyShows(showsInApril);
}

@Test
public void deserializeEmptyMonthlyShows() throws Exception {
String jsonString = "{\"live_shows\":[],\"month\": \"April\"}";
MonthlyShows showsInApril = mapper.readValue(jsonString, MonthlyShows.class);
printOutMonthlyShows(showsInApril);
}

@Test
public void deserializeNoShows() throws Exception {
String jsonString = "{\"month\": \"April\"}";
MonthlyShows showsInApril = mapper.readValue(jsonString, MonthlyShows.class);
System.out.println("month:" + showsInApril.month);
Assert.assertNull(showsInApril.live_shows);
}

@Test
public void deserializeWrongMonthlyShows() throws Exception {
String jsonString = "{\"live_shows\":[{\"showid\":\"showid1\",\"time\":\"14000000000\",\"provider\":1,\"sponser\":\"sponser1\"},{\"showid\":\"showid2\",\"time\":\"15000000000\",\"provider\":2,\"sponser\":\"sponser2\"}],\"month\": \"April\"}";
MonthlyShows showsInApril = mapper.readValue(jsonString, MonthlyShows.class);
printOutMonthlyShows(showsInApril);
}

@Test
public void deserializeTheJsonYouProvide() throws Exception {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"live_shows\":[{\"showid\":\"show1\",\"time\":\"02216629\",\"provider\":0,\"sponser\":\"governmental\"},{\"showid\":\"show2\",\"time\":\"00050340\",\"provider\":2,\"sponser\":\"business\"}],\"month\":\"April\"}";
MonthlyShows showsInApril = mapper.readValue(jsonString, MonthlyShows.class);
printOutMonthlyShows(showsInApril);
}

private void printOutMonthlyShows(MonthlyShows showsInApril) {
System.out.println("month:" + showsInApril.month);
for (LiveShow s : showsInApril.live_shows)
    System.out.println(s.showid + "\t" + s.time + "\t" + s.provider);
}
}

And here is a snippet of my pom.xml:

...
<properties>
    <jackson.version>2.8.6</jackson.version>
</properties>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.fasterxml.jackson</groupId>
            <artifactId>jackson-bom</artifactId>
            <version>${jackson.version}</version>
        </dependency>
    </dependencies>
</dependencyManagement>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.jaxrs</groupId>
        <artifactId>jackson-jaxrs-json-provider</artifactId>
        <version>${jackson.version}</version>
    </dependency>
</dependencies>
...

Upvotes: 1

Phong
Phong

Reputation: 41

Your json string is the wrong format. You declare time as long type, but you send a String value.
Just a little note with a numeric value, A leading zero is not allowed.
For example: "time": 02216629 is wrong. Correctly value is: 22166299

Sometime I want to see a json clearly. I'll create a sample object and print as json value. For example: You can do that too using ObjectMapper.

For example:

ObjectMapper objectMapper = new ObjectMapper();
JsonNode jsonNode = objectMapper.valueToTree(monthlyShows);

Then get a validated json

{"live_shows":[{"showid":"s101","time":1500624568893,"provider":1,"sponser":"ABC sponser"}],"month":"July"}

Upvotes: 1

Related Questions