使用 RestTemplate 将 JSON 字符串(包括不同的宽大)转换为 Java 类 [英] Convert JSON String (Which includes different lenients) to Java Class with RestTemplate
问题描述
我有一个 json 字符串,如:
I have a json string like:
{
"name": "abc",
"type": "type1",
"artist": {
"name": "ally"
},
"other_part": "{\"id\":\"ee50abd7\",\"metadata\":"...\"}"
}
如您所见,other_part"看起来像宽松的格式.它用引号表示.
Like you see, "other_part" looks like in lenient format. It presents with quotation mark.
这里,我只想将其转换为 POJO 类.但是 other_part 给出了解析错误.任何建议.
Here, I just want to convert it to a POJO class. But other_part gives parse error. Any suggestion.
POJO 类:
class Data
{
private String name;
private String type;
private Artist artist;
private Other other_part;
...getters
}
class Artist
{
private String name;
...getters
}
class Other
{
private String id;
private String metadata;
...getters
}
和restTemplate:
and restTemplate:
restTemplate.exchange(requestEntity, Data.class);
错误:
(尽管至少存在一个 Creator):没有从字符串值反序列化的字符串参数构造函数/工厂方法...
(although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value...
谢谢大家解决JsonDeserialize:
public static class OtherConverter extends StdConverter<String, Other>
{
@Override
public Other convert(String value)
{
return new Gson().fromJson(value, Other.class);
}
}
class Data
{
private String name;
private String type;
private Artist artist;
@JsonDeserialize( converter = OtherConverter.class )
private Other other_part;
...getters
}
推荐答案
您可能需要创建自定义解串器.
You will probably need to create a custom deserializer.
@JsonDeserialize(using = CustomDateDeserializer.class)
private Other other_part;
在自定义序列化程序中,您将收到字符串信息.然后您可以使用选择的库转换此字符串.
Inside the custom serializer you will receive the string information. Then you can transform this string using a library of choice.
示例:https://www.tutorialspoint.com/jackson_annotations/jackson_annotations_jsondeserialize.htm
这篇关于使用 RestTemplate 将 JSON 字符串(包括不同的宽大)转换为 Java 类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!