ObjectMapper:如何获取蛇案中的根元素

时间:2018-12-25 06:49:08

标签: java jackson2 jackson-databind

我正在尝试读取对象并转换为字符串。但是根元素从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"
    }
}

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

1 个答案:

答案 0 :(得分:0)

您可以使用以下内容

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反序列化并正确地序列化。