代码之家  ›  专栏  ›  技术社区  ›  user08152017

如何在映射到Java对象时忽略几个JSON元素

  •  0
  • user08152017  · 技术社区  · 5 年前

    我的Spring引导服务处理一个JSON,如下所示

    "Books":[
      {
       "Title": "Title1",
       "Author": "Author1"
      },
      {
       "Title": "Title2",
       "Author": "Author2"
      },
      {
       "Title": "IGNORE",
       "Author": "IGNORE"
      }
    ]
    

    我有一本书

    public class Book{
      @JsonProperty("Title")
      private String title;
      @JsonProperty("Author")
      private String author;
    
      public setters & Getters
      ....
    }
    

    这些书被映射到MyFavBooks.java

    public class MyFavBooks{
      @JsonProperty("Books")
      private Book[] books;
      ....
    }
    

    我试图不映射以下元素(基于标题)。有没有办法做到这一点?

    {
       "Title": "IGNORE",
       "Author": "IGNORE"
    } 
    
    2 回复  |  直到 5 年前
        1
  •  1
  •   ILya Cyclone    5 年前

    您可以尝试使用自定义序列化程序 @JsonSerialize . 大概是这样的:

    public class Book{
      @JsonProperty("Title")
      @JsonSerialize(using = IgnoreSerializer.class)
      private String title;
    
      @JsonProperty("Author")
      @JsonSerialize(using = IgnoreSerializer.class)
      private String author;
    
      public setters & Getters
      ....
    }
    
    public class IgnoreSerializer extends JsonSerializer<String> {
    
        @Override
        public void serialize(String s, 
                              JsonGenerator jsonGenerator, 
                              SerializerProvider serializerProvider) 
                              throws IOException, JsonProcessingException {
            if(!s.equals("IGNORE")) {
                jsonGenerator.writeObject(s);
            }
        }
    }
    

    或者,如果需要基于标题值跳过整个项目,请使用相同的方法定义自定义序列化程序 在你的书本课上。

    @JsonSerialize(using = IgnoreByTitleSerializer.class)
    public class Book{ ... }
    
    class IgnoreByTitleSerializer extends StdSerializer<Book> {
    ...
    @Override
        public void serialize(
          Book book, JsonGenerator jgen, SerializerProvider provider) 
          throws IOException, JsonProcessingException {
            if(!book.getTitle().equals("IGNORE") {
                ...
            }
        }
    }
    
    

    看见 https://www.baeldung.com/jackson-custom-serialization 例如

    upd
    正如Dmitry Bogdanovich公正地提到的,这个问题涉及反序列化,所以我相信您可以使用类似的方法 @JsonDeserialize .

        2
  •  0
  •   Jeff I    5 年前

    例子:

    import java.io.IOException;
    
    import com.fasterxml.jackson.annotation.JsonIgnore;
    import com.fasterxml.jackson.core.JsonGenerationException;
    import com.fasterxml.jackson.databind.JsonMappingException;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.gson.Gson;
    
    public class Book {
        private String title;
        private String author;
    
        @JsonIgnore
        private transient String isbn;
    
    
        public String getTitle() {
            return title;
        }
        public void setTitle(String title) {
            this.title = title;
        }
        public String getAuthor() {
            return author;
        }
        public void setAuthor(String author) {
            this.author = author;
        }
        public String getIsbn() {
            return isbn;
        }
        public void setIsbn(String isbn) {
            this.isbn = isbn;
        }
    
        private static void printGson(Book book) {
            System.out.println("Gson: " + new Gson().toJson(book));
        }
    
        private static void printJackson(Book book) {
            ObjectMapper objectMapper = new ObjectMapper();
    
            try {
                System.out.print("Jackson: ");
                objectMapper.writeValue(System.out, book);
            } catch (JsonGenerationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (JsonMappingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        public static void main(String[] args) {
            Book book = new Book();
            book.setAuthor("Me");
            book.setTitle("Cool");
            book.setIsbn("123");
            printGson(book);
            printJackson(book);
        }
    }
    

    输出:

    Gson: {"title":"Cool","author":"Me"}
    Jackson: {"title":"Cool","author":"Me"}