问题
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