我正在尝试读取对象并转换为字符串。但根元素正在从 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"
}
}
帮我获取输入中的根对象?
最佳答案
您可以按如下方式使用
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 正确地反序列化和序列化。
关于java - 对象映射器 : How to get the root element in snake case,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53920011/