使用具有不同参数的Jackson for List将JSON映射到pojo

时间:2016-04-22 06:31:23

标签: java json exception jackson

JSON格式:

[
{
    "0":
    {
        "cast":"",
        "showname":"woh pagle",
        "type":"Episodes"
    },
    "video":[
        {
            "src":"video.mp4"
        },
        {
            "DRM":"False"
        }
    ]
}
]

这里的问题是我遇到异常:

  

org.codehaus.jackson.map.JsonMappingException:无法反序列化   [来源:START_OBJECT标记中的java.util.ArrayList实例   java.io.StringReader@1c9ca1; line:1,column:55617](通过   参考链:   com.apalya.myplex.valueobject.ThirdPartyContentDetailsArray [ “视频”])

我的pojo课程是:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonProperty("0")
private ThirdPartySubContentDetails subContent;

@JsonProperty("video")
private List<ThirdPartySubContentVideoInfo> video;

My Sub class pojo是:

private String src;

@JsonIgnore
@JsonProperty("DRM")
private String drm;

请帮我写一个视频列表的pojo。

2 个答案:

答案 0 :(得分:1)

您的json以数组开头,而不是对象。要改变的重要部分是Objectmapper应该如何生成你的json。要返回List,您需要这样做:

List<FirstJson> jsonList = mapper.readValue(json, new TypeReference<List<FirstJson>>(){});

这是我在本地实施的简短工作测试:

public static void main(String[] args) {
    String json = "[{\"0\":{\"cast\":\"\",\"showname\":\"wohpagle\",\"type\":\"Episodes\"},\"video\":[{\"src\":\"video.mp4\"},{\"DRM\":\"False\"}]}]";
    ObjectMapper mapper = new ObjectMapper();

    List<FirstJson> jsonList = mapper.readValue(json, new TypeReference<List<FirstJson>>(){});
    System.out.println(jsonList.toString());
}

你在Pojo中的JsonArray的第一部分。(将其命名为FirstJson)

public class FirstJson{

        @JsonProperty("0")
        private FirstJson subContent;

        private String cast;
        private String showname;
        private String type;

        @JsonProperty("video")
        private List<Video> videos;

      //getter/setter

和视频Pojo:

public class Video {

        private String src;

        @JsonProperty("DRM")
        private String drm;

      //getter/setter

只是旁注:如果你在同一个类文件中声明你的pojos,那么这些类应该是静态的。 public static class FirstJson

答案 1 :(得分:1)

根据问题中描述的JSON结构,以下应该是POJO:

public class MainPojo
{
     @JsonProperty("0")
     private ThirdPartySubContentDetails subContent;

     @JsonProperty("video")
     private List<ThirdPartySubContentVideoInfo> video;

     // Getters and Setters for subContent and video
}

class ThirdPartySubContentDetails
{
    private String cast;
    private String showName;
    private String type;

    // Getters and Setters for cast, showName and type
}

@JsonIgnoreProperties(ignoreUnknown = true)
class ThirdPartySubContentVideoInfo
{
    @JsonProperty("src")
    private String src;

    @JsonProperty("DRM")
    private String drm;

    // Getters and Setters for src and drm
}

您应该按如下方式调用反序列化器方法:

 List<MainPojo> list = new ObjectMapper().readValue(json, new TypeReference<List<MainPojo>>(){});