简体   繁体   中英

How to generate JSON and XML from same entity classes?

I have the below class structure.

@XmlSeeAlso({Phone.class, Address.class})
abstract class ContactInfo {

}

@XmlRootElement(name="address")
class Address extends ContactInfo {
    private String street;

    public String getStreet() {
      return street;
    }

    public void setStreet(String street) {
      this.street = street;
    }
}

@XmlRootElement(name="phone")
class Phone extends ContactInfo {
    private String mobile;

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}

class Contact {
    private ContactInfo contact;

    @XmlElementRef
    public ContactInfo getContact() {
        return contact;
    }

    public void setContact(ContactInfo contact) {
        this.contact = contact;
    }
}

@XmlRootElement(name="user")
class User { 
    private String name;
    private Contact contact;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Contact getContact() {
        return contact;
    }
    public void setContact(Contact contact) {
        this.contact = contact;
    }
}

When I convert this to XML using JAXB, I am getting the below structure.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<user>
    <contact>
        <phone>
            <mobile>8971829749</mobile>
        </phone>
    </contact>
    <name>Halley</name>
</user>

Where as my JSON looks a bit different.

{
  "User" : {
    "name" : "Halley",
    "contact" : {
      "contact" : {
        "mobile" : "8971829749"
      }
    }
  }
}

The root element user, and phone is not at all present in my sub JSON structure.

While JAXB is honouring the XMLRootElement annotation, Jackson is not. Any idea why and how I can rectify this?

I need to generate JSON and XML from the same entity classes.

As Jackson is ignoring the element name provided via @XmlRootElement , the Jackson annotations @JsonTypeInfo and @JsonSubTypes should be used to specify which ContactInfo type is Address or Phone . See https://stackoverflow.com/a/6543330/6911095 for an example.

you can use

  • @JsonRootName as class level annotation
  • and ObjectMapper to configure serialization to use root element.

mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);

Using JsonRootName is optional unless you want to have different element name than XML.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM