使用Jackson将JSON反序列化为原始格式的字符串 [英] Deserialize JSON to string in raw format using Jackson

查看:556
本文介绍了使用Jackson将JSON反序列化为原始格式的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用例,我想将JSON原样转换为字符串,但是失败了,并给了我null,这是我的POJO:

I have a use case where I want the JSON to be converted to string as it is, but it is failing and giving me null, here is my POJO:

@Data
@JsonSnakeCase
@JsonIgnoreProperties(ignoreUnknown = true)
public class DocumentTemplateRequest {

@Enumerated(EnumType.STRING)
private TemplateState state;


@JsonDeserialize(using = JsonAsStringDeserializer.class)
private String inputSchema;

}

我正在用作有效负载的Json:

the Json I am using as payload:

{
"state": "staging",
"input_schema": {
    "title": "Person",
    "type": "object",
    "properties": {
        "firstName": {
            "type": "string"
        },
        "lastName": {
            "type": "string"
        }
    },
    "required": ["firstName", "lastName"]
}

}

我正在使用对象映射器进行映射:

I am using object mapper for mappings:

    ObjectMapper objectMapper = new ObjectMapper();
    DocumentTemplateRequest documentTemplateRequest = null;
    try {
        documentTemplateRequest = objectMapper.readValue(str, DocumentTemplateRequest.class);
    } catch (IOException e) {
        e.printStackTrace();
    }

这是我的反序列化器:

public class JsonAsStringDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
    TreeNode tree = jsonParser.getCodec().readTree(jsonParser);
    return tree.toString();

}
}

反序列化的结果是:

state : staging
inputSchema: null

为什么inputSchema为null,我想念什么?

why inputSchema is coming as null, what am I missing?

推荐答案

它是带有属性的吗? 您缺少底线. input_schema与inputSchema不同.

it is with the property? you are missing underscroe. input_schema is different from inputSchema.

要么在您使用的所有地方都使用相同的属性名称,要么使用jsonproperty批注进行区分.

either use the same property name everywhere you use it or use jsonproperty annotation to be sepecific.

这篇关于使用Jackson将JSON反序列化为原始格式的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆