Search code examples
jsonjaxbjackson2

Jackson transforming XML attribute to flat JSON


I have this (imitating actual production data) xml which needs to be converted into JSON as follows.(I am using Jackson2.8):

<testCode code="ABC" lang="java" />

The POJOs i have for this are as follows:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Phone", propOrder = {
  "descriptions"
}
@XmlRootElement(name="phone")
public class Phone extends PhoneBase {

protected TestCode testCode;

getter()
setter();
}

The TestCode is as follows:

XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "TestCode", propOrder = {
"code"
})
public class TestCode {

protected String descriptor;

@XmlAttribute(required = true)       
protected String code;

@XmlAttribute   
protected String lang;
}

On converting it into JSON, i get below:

 testCode: {
 code: "ABC",
 lang: "java"
 }

While i want something as follows:

testCode: "ABC"

Please note, i am ignoring any other attribute and flatening "code". Also, "code" it self is not needed.

Can someone please suggest any pointer? I tried XmlElementWrapper but it did not work.


Solution

  • I was able to resolve it by providing below method in my TestCode class:

       @JsonValue
       public String toJson() {
             return this.code;
       }
    

    Posting it as it might help somebody.