[英]How to convert ArrayList<String> to JSON object using Jackson in Spring @ResponseBody
[英]How to convert json object string to plain string using jackson?
当我在下面有一个 json 时,
{
"test1": "test123",
"test2": {
"a": 1,
"b": 2
}
}
我想使用 Jackson 库将其映射到下面的类。
class TestClass {
String test1;
String test2;
}
但是我不能这样做,因为 test2 是一个 json 对象,而不是 String。 我想将 test1 和 test2 都映射到字符串
String test1; // "test123"
String test2; // "{\"a\": 1, \"b\": 2}"
我应该怎么办?
您应该使用与您的 json 对象相对应的值创建 java 类。 在您的情况下, test1
是 String 对象,而test2
要求您创建将包含两个字符串 ' a
' 和b
的新类。 使用您的方法,在将两个值转换为一个字符串时,您将失去清晰的数据访问权限。
请参阅这些链接以获取更多信息
使用自定义反序列化器。
class TestClass {
String test1;
String test2;
public TestClass(String test1, String test2) {
this.test1 = test1;
this.test2 = test2;
}
}
public class MyDeserializer extends StdDeserializer<TestClass> {
public MyDeserializer() {
this(TestClass.class);
}
public MyDeserializer(Class<?> vc) {
super(vc);
}
@Override
public TestClass deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
JsonNode node = p.getCodec().readTree(p);
return new TestClass(node.get("test1").asText(), node.get("test2").toString());
}
}
测试
String json = "{" +
" \"test1\": \"test123\"," +
" \"test2\": {" +
" \"a\": 1," +
" \"b\": 2" +
" }" +
"}";
ObjectMapper mapper = new ObjectMapper().registerModule(
new SimpleModule().addDeserializer(TestClass.class, new MyDeserializer()));
TestClass testClass = mapper.readValue(json, TestClass.class);
System.out.println(testClass.test1);
System.out.println(testClass.test2);
输出
test123
{"a":1,"b":2}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.