杰克逊将字符串字段解析为JSON

Ros*_*hak 14 java jackson

我有以下JSON:

{
    "some_key": "{\"a\": 1, \"b\": \"text\"}"
}
Run Code Online (Sandbox Code Playgroud)

如您所见,some_keyfield不是JSON对象,它是一个包含有效JSON的字符串.

我想将其解析为以下结构:

class Foo {
    Bar some_key;
}

class Bar {
    int a;
    String b;
}
Run Code Online (Sandbox Code Playgroud)

更新:

  • A和B类,有getter和setter,构造函数.我没有展示它们以保持样品简短.

  • 我无法编辑JSON的奇怪结构.

  • 问题是如何让Jackson将内部字符串字段解析为JSON对象.

df7*_*899 6

@t_liang非常接近 - 只需要比评论更多的空间来展示工作示例......

附:

class Foo {
    @JsonDeserialize(using = BarDeserializer.class)
    private Bar some_key;
}
Run Code Online (Sandbox Code Playgroud)

然后电流ObjectMapper实际上是JsonParser.getCodec():

public class BarDeserializer extends JsonDeserializer<Bar> {
    @Override
    public Bar deserialize(JsonParser p, DeserializationContext ctxt)
            throws IOException, JsonProcessingException {
        String text = p.getText();
        ObjectMapper mapper = (ObjectMapper) p.getCodec();
        return mapper.readValue(text, Bar.class);
    }
}
Run Code Online (Sandbox Code Playgroud)

那么......

ObjectMapper mapper = new ObjectMapper();

Foo foo = mapper.readValue(
        "{ \"some_key\": \"{\\\"a\\\": 1, \\\"b\\\": \\\"text\\\"}\" }",
        Foo.class);

System.out.println(foo.getSome_key());
Run Code Online (Sandbox Code Playgroud)

...显示预期值:

Bar [a=1, b=text]
Run Code Online (Sandbox Code Playgroud)

  • 谢谢您的回答.但是对于'ObjectMapper`来说,这对我来说似乎并不好.我找到了一种避免它的方法:使用`ObjectCodec.getFactory().createParser(...)`创建一个`JsonParser`并将其传递给`ObjectCodec.readValue(...)`.请参阅https://pastebin.com/M22CsAAd (3认同)