user08152017
user08152017

Reputation: 122

How to ignore few JSON elements while mapping to Java Objects

My Spring Boot service process a JSON like this

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

I have a Book.java

public class Book{
  @JsonProperty("Title")
  private String title;
  @JsonProperty("Author")
  private String author;

  public setters & Getters
  ....
}

These books are mapped to MyFavBooks.java

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

I am trying not to map the following element (based on the title). Is there any way to do this?

{
   "Title": "IGNORE",
   "Author": "IGNORE"
} 

Upvotes: 0

Views: 1840

Answers (2)

Jeff I
Jeff I

Reputation: 404

If using gson, transient will work. If using jackson, use @JsonIgnore.

Example:

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

Output:

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

Upvotes: 0

ILya Cyclone
ILya Cyclone

Reputation: 954

You could try custom serializers using @JsonSerialize. Something like this:

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

Or if you need to skip the whole item based on Title value, define custom serializer using the same @JsonSerialize on your Book class.

@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") {
            ...
        }
    }
}

See https://www.baeldung.com/jackson-custom-serialization for example.

upd
As Dmitry Bogdanovich fairly mentioned, question concerns deserialization, so I believe you could go the similar way using @JsonDeserialize.

Upvotes: 1

Related Questions