Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

spring boot - Convert JSON String (Which includes different lenients) to Java Class with RestTemplate

I have a json string like:

{
   "name": "abc",
   "type": "type1",
   "artist": {
       "name": "ally"
   },
   "other_part": "{"id":"ee50abd7","metadata":"..."}"
}

Like you see, "other_part" looks like in lenient format. It presents with quotation mark.

Here, I just want to convert it to a POJO class. But other_part gives parse error. Any suggestion.

POJO Class:

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
} 

and restTemplate:

restTemplate.exchange(requestEntity, Data.class);

Error:

(although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value...

Thanks guys solved with 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
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Example: https://www.tutorialspoint.com/jackson_annotations/jackson_annotations_jsondeserialize.htm


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...