使用jackson ObjectMapper将Json映射到java对象,得到错误

时间:2014-09-02 04:30:59

标签: java json jackson

我有以下json字符串,我想读入java对象,我收到以下错误

JSON

{"models":[{"id":6002,"publisherName":"AbacusT","active":false}]}

解析java

Publisher publisher = new ObjectMapper().readValue( " {\"models\":[{\"id\":6002,\"publisherName\":\"AbacusT\",\"active\":false}]}", Publisher.class); 

错误

21:21:24,878 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/wad].[springMain]] (http--127.0.0.1-8080-1) Servlet.service() for servlet springMain threw exception: org.codehaus.jackson.map.exc.UnrecognizedPropertyException: Unrecognized field "models" (Class com.guthyrenker.wad.core.model.lookup.PublisherLookupItem), not marked as ignorable
 at [Source: java.io.StringReader@418bd56d; line: 1, column: 12] (through reference chain: com.guthyrenker.wad.core.model.lookup.PublisherLookupItem["models"])

代码

// Java class
public class Publisher {



    private Integer id;


    private String publisherName;


    private boolean active;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getPublisherName() {
        return publisherName;
    }

    public void setPublisherName(String publisherName) {
        this.publisherName = publisherName;
    }

    public boolean isActive() {
        return active;
    }

    public void setActive(boolean active) {
        this.active = active;
    }
}

1 个答案:

答案 0 :(得分:1)

您的Publisher类型没有models属性。因此,无法从JSON映射名为models的根条目。你需要的是一个映射到给定JSON的POJO。

如果我们格式化它,我们得到

{
    "models": [
        {
            "id": 6002,
            "publisherName": "AbacusT",
            "active": false
        }
    ]
}

根对象有一个名为models的条目,它是一个JSON数组。该数组包含一个JSON对象。 JSON对象有三个映射到Publisher POJO的条目。因此,您需要包含POJO,其中包含Publisher的某个集合类型(或数组)的单个字段。

这样的东西
public class PublisherModels {
    private List<Publisher> models;
    // getters and setters
}

然后使用此ObjectMapper代替此Publisher

PublisherModels publisherModels = new ObjectMapper().readValue( " {\"models\":[{\"id\":6002,\"publisherName\":\"AbacusT\",\"active\":false}]}", PublisherModels.class); 

如果您要使PublisherModels通用,那么您必须使用类型令牌(在您最喜欢的搜索引擎上查找)。杰克逊为此目的实施了TypeReference

new TypeReference<PublisherModels<PublisherLookupItem>>() {};

您可以将该对象传递给ObjectMapper#readValue(..)方法。