【问题标题】:Adding the name of the class to the json [duplicate]将类的名称添加到 json [重复]
【发布时间】:2019-03-25 10:53:31
【问题描述】:

我是 Java 中 json 和 objectMapper 的新手,我有一个有两个字段的类,我想创建这个类的 json,但我只使用映射器的属性。我该怎么做?

public class Car{
   String a;
   String b;

}

ObjectMapper mapper;
String car = mapper.writeValueAsString(new Car(a, b));

json:

"{a: a, b: b}"

我想要什么:{Car: { a: a, b: b } }

【问题讨论】:

  • 请注意,像 Jackson 这样的库支持这样的东西。为什么你想要 json 中的类?如果您有 2 辆或更多汽车,该怎么办?应该是[{"Car":{...}},{"Car":{...}}, ...]
  • @Thomas 你是对的。 Here is a common SO question.

标签: java json objectmapper


【解决方案1】:

通过使用 JACKSON,您可以通过使用 JsonRootName 注释来实现这一点。

您可以将它添加到您的类上方,并使用您希望它作为 JSON 根元素的值。 在您的情况下,您应该执行以下操作:

@JsonRootName(value = "car")
@JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT ,use = JsonTypeInfo.Id.NAME)
public class Car{
...
} 

如您所见,我们还添加了JsonTypeInfo 注释,这是必要的,因为它指示应使用哪种类型的包装。

如果您希望根字段与类名具有相同的值,您也可以去掉 @JsonRootName(value = "Car") 并仅使用 @JsonTypeInfo(include = JsonTypeInfo.As.WRAPPER_OBJECT ,use = JsonTypeInfo.Id.NAME)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 2023-01-11
    • 1970-01-01
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多