Deserialize JSON to string in raw format using Jackson

夙愿已清 提交于 2019-12-25 08:59:26

问题


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;

}

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

and here is my deserializer:

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

}
}

and the results of deserialization is :

state : staging
inputSchema: null

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


回答1:


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

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



来源:https://stackoverflow.com/questions/43117558/deserialize-json-to-string-in-raw-format-using-jackson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!