Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson Converting String to Object

Link.java

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({ "rel", "href","method" })
public class Link {

    @JsonProperty("rel")
    private String rel;
    @JsonProperty("href")
    private String href;
    @JsonProperty("method")
    private Method method;

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}

I have this third party class with fasterxml jackson annotations. I can convert a given object into a string using the specified toString() method. Is there any way of using that String to get an object of type Link?

Note: The object itself has an embedded object (which has several more embedded objects) and these too needs to be converted into a Method object from the string itself.

like image 510
ytibrewala Avatar asked May 05 '17 12:05

ytibrewala


People also ask

How does Jackson convert object to JSON?

Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.


1 Answers

Just putting the comment by @pvpkiran in an answer.

Use ObjectMapper class from com.fasterxml.jackson.databind

ObjectMapper objectMapper = new ObjectMapper();

Converting from Object to String:

String jsonString = objectMapper.writeValueAsString(link);

Converting from String to Object:

Link link = objectMapper.readValue(jsonString, type)
like image 105
ytibrewala Avatar answered Oct 06 '22 04:10

ytibrewala