简体   繁体   中英

Convert JSON to JAVA by jackson

I'm trying to parse json data retrieved from google custom search.

Here is the json example:

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

And this is the POJO:

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

But I get an error:

Unrecognized field "items" (Class Result), not marked as ignorable

What wrong with my 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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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