杰克逊要解析复杂的物体

时间:2017-07-21 07:22:21

标签: java json parsing jackson

我想用jackson解析json对象。我的对象结构是这样的: 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;
    }
}

我如何解析对象:

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

我得到了空指针异常,我理解这意味着我无法解析这样的复合/复杂对象。

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)
月份:4月

有办法解决这个问题吗?

修改

json对象的例子我解析的是:

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

我在下面的评论中修正了Nico指出的属性类型。 +按要求提供完整的课程

2 个答案:

答案 0 :(得分:1)

您的json字符串格式错误。您将时间声明为long类型,但是您发送一个String值 只是带有数值的小注,不允许前导零 例如:&#34;时间&#34;:02216629错误。正确的价值是:22166299

有时我想清楚地看到一个json。我将创建一个示例对象并打印为json值。例如: 你也可以使用ObjectMapper。

例如:

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

然后获得经过验证的json

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

答案 1 :(得分:1)

您可以使用@JsonInclude(Include.NON_NULL)来避免对null属性进行反序列化:

@JsonInclude(Include.NON_NULL)
public class MonthlyShows {

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

以这种方式更改MonthlyShows构造函数:

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

以下是完整的代码示例:

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

这是我的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>
...