【问题标题】:ObjectMapper : How to get the root element in snake caseObjectMapper:如何在蛇案例中获取根元素
【发布时间】:2019-05-24 00:07:44
【问题描述】:

我正在尝试读取对象并转换为字符串。但是根元素正在从payment_token 更改为PaymentToken

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
String requestString = mapper.writeValueAsString(paymentToken); //paymenttoken is valid object

输入对象:

{
    "payment_token": {
        "client_id": "test",
        "currency_code": "USD" 
    }
}

获取输出为:

{
    "PaymentToken": {
        "client_id": "test",
        "currency_code": "USD"
    }
}

帮我获取输入中的根对象?

【问题讨论】:

  • 您的 JSON 已损坏。 paymentToken 也不清楚。您能否添加您如何构建 paymentToken 以及它是否也具有 DTO 类共享。

标签: java jackson2 jackson-databind


【解决方案1】:

你可以如下使用

import com.fasterxml.jackson.annotation.JsonRootName;
@JsonRootName(value = "payment_token")
public class PaymentToken {
...
}

参考:JsonRootName

如果你添加上面的注释,让我们看看它是如何工作的
在 ObjectMapper 中添加如下配置

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.SerializationFeature;

ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); // additional to your config
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
String paymentToken = "{\"payment_token\":{\"client_id\":\"test\",\"currency_code\":\"USD\"}}";

System.out.println(mapper.readValue(paymentToken, PaymentToken.class));
System.out.println(mapper.writeValueAsString(paymentToken));

输出:

PaymentToken(clientId=test, currencyCode=USD)
{"String":"{\"payment_token\":{\"client_id\":\"test\",\"currency_code\":\"USD\"}}"}

如上所见,objectMapper 正确反序列化和序列化。

【讨论】:

  • 我无权访问这个类,有没有mapper配置?
  • 不需要任何配置,您使用的是哪个 Jackson 版本?添加com.fasterxml.jackson.core:jackson-core:2.4.x作为依赖,版本应该>= 2.4.0,我用的是2.9.8版本
  • 我正在使用2.9.6 版本。不知道为什么它返回根元素PaymentToken。因为我没有课程,所以我不能在 pojo 中使用注释。
  • 你的意思是你不想要字符串中的“PaymentToken”键并且只想要{"client_id":"test","currency_code":"USD"}
  • 我的问题在这里,正如问题Help me to get the root object as it is in input
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-25
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
  • 2018-02-15
相关资源
最近更新 更多