杰克逊反序列化列表,跳过没有特定字段的元素

时间:2017-03-27 10:37:09

标签: java json serialization jackson

我想将杰克逊的JSON反序列化为 CREATE TABLE orders (`id` int(11), `name` varchar(7), `order_date` datetime) ; INSERT INTO orders (`id`, `name`, `order_date`) VALUES (1, 'order 1', '2014-01-01 00:00:00'), (2, 'order 2', '2015-01-01 00:00:00'), (3, 'order 3', '2016-01-01 00:00:00') ; CREATE TABLE orderline (`id` int, `Order_id` int, `order_status` varchar(8), `status_date` datetime) ; INSERT INTO orderline (`id`, `Order_id`, `order_status`, `status_date`) VALUES (1, 1, 'New', '2014-01-01 00:00:00'), (2, 1, 'Shipped', '2014-10-01 00:00:00'), (3, 2, 'New', '2015-01-01 00:00:00'), (4, 2, 'Canceled', '2015-03-01 00:00:00'), (5, 3, 'New', '2016-01-01 00:00:00'), (6, 3, 'Canceled', '2016-02-01 00:00:00') ; 喜欢

List<User>

我想:

  • class Users { private List<User> users; } class User { private Integer id; private String name; } 是必填字段,因此如果用户元素不包含ID,则应跳过该
  • id被认为是可选的,因此如果用户元素不包含名称,则应将其包含在具有name名称的列表中(如果可能,甚至包含Java 8可选值)< / LI>

例如,在以下JSON中

null

在反序列化期间应该跳过第二个用户,第三个用户应该包含在具有空名称的列表中。 是否有可能使用杰克逊?

3 个答案:

答案 0 :(得分:1)

我认为自定义反序列化器可以执行如下所示的任务。

    public class UserListDeserializer extends JsonDeserializer<List<User>> {

    @Override
    public List<User> deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        JsonNode node = p.readValueAsTree();
        Iterator<JsonNode> it = node.elements();
        List<User> userList=new ArrayList<>();
        while (it.hasNext()) {
            JsonNode user = it.next();
            if (user.get("id") != null) {
                User userObj = new User();
                userObj.setId(user.get("id").intValue());
                userObj.setName(user.get("name")!=null?user.get("name").textValue():null);
                userList.add(userObj);
            }

        }
        return userList;
    }
}

并注释您的Users类,如下所示。

public class Users {
    @JsonDeserialize(using=UserListDeserializer.class)
    private List<User> users;
}

答案 1 :(得分:0)

您可以过滤设置器中不需要的项目:

public void setUsers(List<User> users) {
    this.users = users.stream().filter(u -> u != null && u.id != null).collect(Collectors.toList());
}

这是我的完整测试课程:

public static void main(String[] args)
{
    String json = "{ \"users\" : [{\"id\" : 123, \"name\" : \"Andrew\"}, {\"name\" : \"Bob\"}, {\"id\" : 789}]}";
    try {
        ObjectMapper mapper = new ObjectMapper();
        Users users = mapper.readValue(json, Users.class);
        System.out.println(users.users);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static class Users
{
    private List<User> users;

    public void setUsers(List<User> users)
    {
        this.users = users.stream().filter(u -> u != null && u.id != null).collect(Collectors.toList());
    }
}

public static class User
{
    public Integer id;
    public String name;
    @Override
    public String toString()
    {
        return"{id=" + id + ", name=" + name + "}";
    }
}

输出:

[{id=123, name=Andrew}, {id=789, name=null}]

答案 2 :(得分:0)

您可以使用com.fasterxml.jackson.annotation执行此操作。

这样的事情:):

     public static void main(String[] args)  {
          String json = "{ \"users\" : [{\"id\" : 123, \"name\" : \"Andrew\"}, {\"name\" : \"Bob\"}, {\"id\" : 789}]}";
          try {
            ObjectMapper mapper = new ObjectMapper();
            Users users = mapper.readValue(json, Users.class);

       String jsonInString= mapper.writeValueAsString(selectUsers(users.getUsers()));
            System.out.println(jsonInString);

          } catch (Exception e) {
            e.printStackTrace();
          }
        }

  private static Collection<User> selectUsers(List<User> users) {
    return org.apache.commons.collections4.CollectionUtils.select(users, new org.apache.commons.collections4.Predicate<User>() {

      @Override
      public boolean evaluate(User user) {
        return user.getId() != null;
      }

    });
  }

     public static class Users implements Serializable {



        private List<User> users;

        /**
         * @return the users
         */
        public List<User> getUsers() {
          return users;
        }

        /**
         * @param users the users to set
         */
        public void setUsers(List<User> users) {
          this.users = users;
        }

      }
      @JsonIgnoreProperties(ignoreUnknown = true)
      public static class User implements Serializable {

        /**
         * 
         */
        private static final long serialVersionUID = 4223240034979295550L;

        @JsonInclude(JsonInclude.Include.NON_NULL)
        public Integer id;

        @NotNull
        public String name;

        /**
         * @return the id
         */
        public Integer getId() {
          return id;
        }

        /**
         * @param id the id to set
         */
        public void setId(Integer id) {
          this.id = id;
        }

        /**
         * @return the name
         */
        public String getName() {
          return name;
        }

        /**
         * @param name the name to set
         */
        public void setName(String name) {
          this.name = name;
        }
      }

输出:[{“id”:123,“name”:“Andrew”},{“id”:789,“name”:null}]