0

I have the user table stored as following:

|---------------------|------------------|-------------------------------------------------------------|
|      id             |     name         |    address                       
|---------------------|------------------|-------------------------------------------------------------|
|      1              |     ken          | {"street":"Street 1","city":"City1", "country":"USA"}       |     
|---------------------|------------------|-------------------------------------------------------------|

My POJO:

public class User{
   private int id;
   private String name;
   private String address;
    //setters and getters
}

In my RESTful services i wish to have the following JSON as response when i call for my API:

{
   "id": 1,
   "name": "ken",
   "address":{
        "street":"Street 1",
        "city":"City1", 
        "country":"USA"
   }
}

I can do this by changing my address in POJO to a address object, then map the string into the adress object.

But is there any other ways that i keep my address as string in POJO, then it will render as JSON?

1 Answer 1

3

you can use @JsonSerialize on your property:

@JsonSerialize(using = CustomeSerializer.class)
private String address;


public class CustomSerializer extends StdSerializer<String>{
    public CustomSerializer(){
        this(null);
    }
    public CustomSerializer(Class<String> t) {
        super(t);
    }

    @Override
    public void serialize(String address, JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider) throws IOException {
        jsonGenerator.writeObject(new ObjectMapper().readTree(address));
    }
}
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.