开发者

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

开发者 https://www.devze.com 2023-03-18 13:27 出处:网络
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 w

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 whi开发者_StackOverflowch we can specify don't convert this class varaible into JSON.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号