2017-03-27 1 views
1

없는 요소를 건너 뜁니다잭슨의 직렬화는, 내가 좋아하는 것 <code>List<User></code><p><pre><code>class Users { private List<User> users; } class User { private Integer id; private String name; } </code></pre> </p> 좋아하는 내가 잭슨와 JSON을 역 직렬화하고 싶은 특정 필드

  • id는 필수 필드로, 따라서 사용자 요소에 ID가 포함되어 있지 않으면 생략해야합니다.
  • name 선택 사항이므로 사용자 요소에 이름이 없으면와 함께 목록에 포함해야합니다 7,이름 (또는 자바 8 옵션 값이 가능하다면) 번째 사용자가 직렬화 중에 생략한다

    { 
        "users" : [{ 
          "id" : 123, 
          "name" : "Andrew" 
         }, { 
          "name" : "Bob" 
         }, { 
          "id" : 789 
         }, 
         ... 
        ] 
    } 
    

    다음 JSON 예 이처럼

, 세번째가 포함되어야 하늘의 이름을 가지는리스트 Jackson을 사용하는 것이 가능합니까?

+0

이 https://github.com/FasterXML/jackson-annotations/wiki/Jackson-Annotations를 확인하십시오. 작성한 디시리얼라이저 코드를 표시하십시오. –

+0

id 속성에 @JsonProperty (필수 = true)를 시도 했습니까? – Jayz

+0

@DhruvPal 필자는 ObjectMapper를 사용하는 Feign 클라이언트를 사용합니다. @ Jayz 시도했지만, id가없는 항목은 null id 값에 포함됩니다. – kornisb

답변

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}]

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

다음과 같이 사용자 클래스에 주석을 답니다.

public class Users { 
    @JsonDeserialize(using=UserListDeserializer.class) 
    private List<User> users; 
} 
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, "이름": "앤드류"}, { "ID": 789, "이름": 널 (null)}]