【问题标题】:how to change property or field name in a custom json serializer如何更改自定义 json 序列化程序中的属性或字段名称
【发布时间】:2018-02-27 02:13:46
【问题描述】:

我有一个字段的自定义序列化程序。

public class SearchSerialize extends StdSerializer<Value> {

public SearchSerialize() {
    super(Value.class);
}
@Override
public void serialize(Value value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

    if("database".equals(jsonGenerator.getOutputContext().getCurrentName())&&"abc".equals(value.getValue()))
        //change field name "database to "branchmark"
    else
        jsonGenerator.writeString(value.getValue());

}
}

它的值决定了字段名是否改变,所以我不知道如何处理这个。 使用杰克逊 2.9.0 谢谢!

【问题讨论】:

  • 您不能更改名称。

标签: java json jackson


【解决方案1】:

看看这个

public class Response {
  private String status;
  private String error;

  @JsonProperty("p")
  @JsonSerialize(using = CustomSerializer.class)
  private Object data;

  // ...
}

public class CustomSerializer extends JsonSerializer<Object> {
  public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    jgen.writeStartObject();
    jgen.writeObjectField(value.getClass().getName(), value);
    jgen.writeEndObject();
  }
}

public static void main(String... args) throws Exception {
  ObjectMapper mapper = new ObjectMapper();
  Response r1 = new Response("Error", "Some error", 20);
  System.out.println(mapper.writeValueAsString(r1));
  Response r2 = new Response("Error", "Some error", "some string");
  System.out.println(mapper.writeValueAsString(r2));
}

[来源]

Jackson dynamic property names

【讨论】:

  • 非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-01
  • 1970-01-01
  • 2021-08-22
  • 1970-01-01
  • 2023-03-03
  • 1970-01-01
相关资源
最近更新 更多