Json version of XMLElements choice
Asked Answered
A

1

11

For a Java code with the following annotation:

@JsonProperty(value="Contact")
    @NotNull(message = "ContactUser or CompanyName is required.")
    @Valid
    @XmlElements(value = {
            @XmlElement(name = "ContactUser", type = ContactUser.class, required = true),
            @XmlElement(name = "CompanyName", type = String.class, required = true) })  
    private Object contactInfo;

Result set when I use the object for GET is :

"Contact": {
    "ContactUser": {
        "Title": "Miss",
        "LastName": "Hello"
    }
}

or

"Contact": "Hello Company"

Is there a way so it returns:

"ContactUser": {
    "Title": "Miss",
    "LastName": "Hello"
}

or

"CompanyName": "Hello Company"

instead? In xml, with the code, you can do:

 <CompanyName>Hello Company</CompanyName>

or

<ContactUser>
    <Title>Miss</Title>
    <LastName>Hello</LastName>
</ContactUser>

I have tried using JsonTypeInfo but it doesnt seem to handle String.class:

 @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include =JsonTypeInfo.As.WRAPPER_OBJECT, visible=true)
    @JsonSubTypes({
        @JsonSubTypes.Type(name = "ContactUserJ", value = ContactUser.class),
        @JsonSubTypes.Type(name = "CompanyNameJ" , value = String.class)
    })
Aril answered 16/1, 2018 at 11:2 Comment(3)
The Object type is too generic it seems.Bladdernose
I think you want to return one or another depending of what info is filled?Subinfeudate
I think if Object contactInfo is an instance of a Map easily you can add a conditional to put the key and value if ContactUser or CompanyName is presentSubinfeudate
S
0

Are you using spring?. I used a simple java class In simple java I got

{
   "ContactUser" : {
    "Title" : "sampleTitle",
    "LastName" : "sampleLastName"
     },
    "CompanyName" : "XXXXX"
}

Could you rephrase your question. I think I quite not understand what is your intend.

This is my code:

@JsonProperty(value = "Contact")
@XmlElements(value = {
    @XmlElement(name = "ContactUser", type = ContactUser.class, required = true)
    ,
        @XmlElement(name = "CompanyName", type = String.class, required = true)})
private Object contactInfo;

public TestClassConstructor() throws JsonProcessingException {
    contactInfo = new HashMap<String, Object>();
    ((HashMap) contactInfo).put("ContactUser", new ContactUser("sampleTitle", "sampleLastName"));
    ((HashMap) contactInfo).put("CompanyName", "XXXXX");

    ObjectMapper mapper = new ObjectMapper();
    String jsonResult = mapper.writerWithDefaultPrettyPrinter()
            .writeValueAsString(contactInfo);
    System.err.println(jsonResult);
}

In case you wanted to have a specific serializer you need to check: http://www.baeldung.com/jackson-serialize-field-custom-criteria

Subinfeudate answered 26/1, 2018 at 14:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.