エランMorad:
私は、ジャクソンは、このようなクラスを注釈を付けています:
public class MyClass {
String field1;
@JsonIgnore
String field2;
String field3;
@JsonIgnore
String field4;
}
私は、MyClassのコードを変更することはできませんと仮定します。次に、どのように私はObjectMapperが唯一のフィールド2のためJsonIgnoreをオーバーライドして、JSONに、それをシリアル化することができますか?私はそれがFIELD4かかわらを無視したいです。コードのこの簡単で数行ですか?
通常の直列化のための私のコード:
public String toJson(SomeObject obj){
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = null;
try {
json = ow.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return json;
}
マイケルZiober:
あなたは使用することができますMixIn
機能:
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
public class JsonApp {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
mapper.addMixIn(MyClass.class, MyClassMixIn.class);
System.out.println(mapper.writeValueAsString(new MyClass()));
}
}
interface MyClassMixIn {
@JsonProperty
String getField2();
}
上記のコードを印刷:
{
"field1" : "F1",
"field2" : "F2",
"field3" : "F3"
}