Sapan Diwakar
Sapan Diwakar

Reputation: 10966

How can I control which instance variables are serialized when using Jackson JSON

I am using JSON Jackson to convert from POJOs to JSON. I am using

mapper.writeValueAsString(s);

It is working fine. Problem is I dont't want to convert all class varaibles into JSON. Anyone kno whow to do it; is there any function for ObjectMapper in which we can specify don't convert this class varaible into JSON.

Upvotes: 0

Views: 3401

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340883

Annotate fields you want to ignore with @JsonIgnore (JavaDoc).

Upvotes: 3

Programmer Bruce
Programmer Bruce

Reputation: 66963

Here are examples of using @JsonIgnore and @JsonIgnoreType to either ignore a specific property or to ignore all properties of a specific type.

import org.codehaus.jackson.annotate.JsonIgnore;
import org.codehaus.jackson.annotate.JsonIgnoreType;
import org.codehaus.jackson.map.ObjectMapper;

public class JacksonIgnoreFieldsDemo
{
  public static void main(String[] args) throws Exception
  {
    ObjectMapper mapper = new ObjectMapper();

    String json1 = mapper.writeValueAsString(new Bar());
    System.out.println(json1); // {"a":"A"}

    // input: {"a":"xyz","b":"B"}
    String json2 = "{\"a\":\"xyz\",\"b\":\"B\"}";
    Bar bar = mapper.readValue(json2, Bar.class);
    System.out.println(bar.a); // xyz
    System.out.println(bar.b); // B

    System.out.println();
    System.out.println(mapper.writeValueAsString(new BarContainer()));
    // output: {"c":"C"}
  }
}

class BarContainer
{
  public Bar bar = new Bar();
  public String c = "C";
}

@JsonIgnoreType
class Bar
{
  public String a = "A";
  @JsonIgnore
  public String b = "B";
}

More options are outlined in my blog post at http://programmerbruce.blogspot.com/2011/07/gson-v-jackson-part-4.html


Updated to correct copy-paste mistake.

Upvotes: 1

Related Questions