16

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.

ytibrewala
  • 957
  • 1
  • 8
  • 12
  • 2
    don't use toString Use jackson ObjectMapper::readValue and ObjectMapper::writeValueAsString – pvpkiran May 05 '17 at 12:16
  • 1
    Use `new ObjectMapper().readValue(jsonString, Link.class);` – Praneeth Ramesh May 05 '17 at 12:18
  • 1
    @pvpkiran ... although `ToStringBuilder` can be configured to output JSON, which `ObjectMapper` would be able to consume. – slim May 05 '17 at 12:24
  • 1
    yes you can but there are cases where toString() performs very badly expecially in cases of nested objects and collections.Try printing a map or list with toString and also with ObjectMapper and see the difference – pvpkiran May 05 '17 at 12:27

1 Answers1

57

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)
ytibrewala
  • 957
  • 1
  • 8
  • 12