I would like serialize an object such that one of the fields will be named differently based on the type of the field. For example:

public class Response {
    private Status status;
    private String error;
    private Object data;
        [ getters, setters ]
    }

Here, I would like the field data to be serialized to something like data.getClass.getName() instead of always having a field called data which contains a different type depending on the situation.

我怎样才能用杰克逊达到这样的目的呢?

推荐答案

Using a custom JsonSerializer.

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

And then, suppose you want to serialize the following two objects:

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

第一个将打印:

{"status":"Error","error":"Some error","p":{"java.lang.Integer":20}}

第二个是:

{"status":"Error","error":"Some error","p":{"java.lang.String":"some string"}}

I have used the name p for the wrapper object since it will merely serve as a placeholder. If you want to remove it, you'd have to write a custom serializer for the entire class, i.e., a JsonSerializer<Response>.

Json相关问答推荐

使用SQL查询从SON中查找第n个密钥对值

如何使用ChoETL将复杂的JSON转换为CSV

服务器不返回JSON

给定一个包含两个数组的JSON输入文件,如何使用Jolt将一个数组中的每个元素与另一个数组组合在一起?

使用 jq,如何将两个属性构成键的对象数组转换为对象的索引对象?

如何将具有相同 struct 的多个JSON文件中的对象数组合并成一个数组?

错误解析错误:意外令牌:在我的 .eslintrc.json 文件中.为什么?

jq EOF 处的无效数字文字将 json 值更新为 0.0.x

如何加入或合并列表元素列表(未知长度)

将具有多个级别的 json 读入 DataFrame [python]

用powershell条件解析json文件的数组对象

Scala - 在构建 Json 时无法删除 Key -> value "{}" 大括号的双引号

如何在循环中传递列表(会话(字符串属性))以在 Gatling Scala 中创建批量 Json 请求

JQuery,使用 GET 方法发送 JSON 对象

如何使用 Kotlin + Jackson 将 JSON 反序列化为 List

如何使用 json.net 将数据表转换为 json 字符串?

在自定义 JsonConverter 的 ReadJson 方法中处理空对象

JSON Schema:验证数字或空值

在 React 中访问子级的父级状态

在没有 ASP.NET Core 的情况下将 IConfigurationSection 绑定到复杂对象