I have an entity like
@Getter
@Setter
public class MyObject {
private String name;
private String extension;
}
I need to generate (for a web service) following JSON:
{
"name" : "Hein Blöd"
"extension:anybill" : "blah blah"
}
To generate the JSON I use javax.ws.rs.client.Entity.json(myObject)
. The problem is the ":" in the second attribute (because ":" is an invalid character for variable names). Is there any annotation to specify the name of attribute key? Or can I rename the generated JSON attribute in any other way?
CodePudding user response:
I don’t recommend mixing JAX-RS and Jackson. Since you are using javax.ws.rs.client.Entity, you should use @JsonbProperty, which is part of Java EE’s JSON-P and which is intended to work with JAX-RS, on your entity class:
@JsonbProperty("extension:anybill")
private String extension;
CodePudding user response:
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
public static void main(String... args) throws IOException {
MyObject obj = new MyObject();
obj.name = "Hein Blöd";
obj.extension = "blah blah";
String json = new ObjectMapper().writeValueAsString(obj);
MyObject res = new ObjectMapper().readValue(json, MyObject.class);
}
public static class MyObject {
@JsonProperty("name")
private String name;
@JsonProperty("extension:anybill")
private String extension;
}