简体   繁体   English

如何使用杰克逊将 json 对象字符串转换为纯字符串?

[英]How to convert json object string to plain string using jackson?

When I have a json below,当我在下面有一个 json 时,

{
    "test1": "test123",
    "test2": {
        "a": 1,
        "b": 2
    }
}

I want to map this to below class using Jackson library.我想使用 Jackson 库将其映射到下面的类。

class TestClass {
    String test1;
    String test2;
}

But I can't do this because test2 is an json object, not String.但是我不能这样做,因为 test2 是一个 json 对象,而不是 String。 I want to map both test1 and test2 to string我想将 test1 和 test2 都映射到字符串

String test1; // "test123"
String test2; // "{\"a\": 1, \"b\": 2}"

What should I do?我应该怎么办?

You should create java class with values that corresponds to you json object.您应该使用与您的 json 对象相对应的值创建 java 类。 In your case test1 is String object and test2 requires you to create new class that will hold two strings ' a ' and b .在您的情况下, test1是 String 对象,而test2要求您创建将包含两个字符串 ' a ' 和b的新类。 With your approach you will lose clear data access when converting two values into one String.使用您的方法,在将两个值转换为一个字符串时,您将失去清晰的数据访问权限。

Please refer to those links for more information请参阅这些链接以获取更多信息

Use custom deserializer.使用自定义反序列化器。


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());
    }
}

Test测试

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);

Output输出

test123
{"a":1,"b":2}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM