简体   繁体   English

通过Jackson将JSON转换为JAVA

[英]Convert JSON to JAVA by jackson

I'm trying to parse json data retrieved from google custom search. 我正在尝试解析从Google自定义搜索中检索到的json数据。

Here is the json example: 这是json示例:

{
 "items": [
  {
   "link": "address1"
  },
  {
   "link": "address2"
  }
 ]
}

And this is the POJO: 这是POJO:

public class Result 
{
    item[] items;
    class item
    {
        String link;
    }
}

But I get an error: 但是我得到一个错误:

Unrecognized field "items" (Class Result), not marked as ignorable 无法识别的字段“ items”(类结果),未标记为可忽略

What wrong with my POJO? 我的POJO有什么问题?

Make the class structure like below 使类结构如下

class item {
    String link;
}
@JsonIgnoreProperties(ignoreUnknown=true)
class Result {
    item[] items;
}

The @JsonIgnoreProperties(ignoreUnknown=true) will be help full if there is any properties in JSON string but that is not in your class then parser won't through any exception it will simply ignore it. 如果JSON字符串中有任何属性,但是@JsonIgnoreProperties(ignoreUnknown = true)会完全帮助您,但类中不存在该属性,那么解析器不会遇到任何异常,它只会忽略它。

EDIT: Complete code with Example 编辑:带有示例的完整代码

class Item {
    String link;

    public String getLink() {
        return link;
    }

    public void setLink(String link) {
        this.link = link;
    }
}

@JsonIgnoreProperties(ignoreUnknown = true)
class Result {
    List<Item> items;

    public List<Item> getItems() {
        return items;
    }

    public void setItems(List<Item> items) {
        this.items = items;
    }

} }

public class JsonCommonTest {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String data = "{\"items\": [{\"link\": \"address1\"},{\"link\": \"address2 \"}]}";
        Result result = mapper.readValue(data, Result.class);
        System.out.println(result.items.size());
    }
}

如果在杰克逊中使用内部类,则内部类必须是静态的,或者不要使用内部类。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM