0

I will get a JSON in the following format

"address":
{
   "type": "Temporary"
}

Following is the Address class.

class Address
{
    AddressType type;
    public Address(AddressType type)
    {
        this.type = type;
    }
}

class AddressType
{
    private String type;
    public AddressType(String type)
    {
        this.type = type;
    }
}

If Address.java had type as String, it would have been easier to transform from JSON to Address object. But I am not sure how I can transform the JSON to Address object where "type" will get transformed to AddressType object. I will use Jackson library. Please help me.

1 Answer 1

1

For AddressType itself, that should work just as it is, since Jackson will convert a string to an object where the object has a public constructor taking a single string.

For serialization, you may want to annotate the type field or getType method with @JsonValue to perform the reverse transformation.

To have the Address constructor called with the type given, you need the @JsonCreator annotation on the constructor, and @JsonProperty annotations on its parameters:

@JsonCreator
public Address(@JsonProperty("type") AddressType type) { ... }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.