Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize JAXB object to JSON with JAXB reference implementation?

Tags:

json

jaxb

The project I'm working on uses the JAXB reference implementation, i.e. classes are from the com.sun.xml.bind.v2.* packages.

I have a class User:

package com.example;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "user")
public class User {
    private String email;
    private String password;

    public User() {
    }

    public User(String email, String password) {
        this.email = email;
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

I want to use a JAXB marshaller to get a JSON representation of a User object:

@Test
public void serializeObjectToJson() throws JsonProcessingException, JAXBException {
    User user = new User("[email protected]", "mySecret");
    JAXBContext jaxbContext = JAXBContext.newInstance(User.class);

    Marshaller marshaller = jaxbContext.createMarshaller();

    StringWriter sw = new StringWriter();
    marshaller.marshal(user, sw);

    assertEquals( "{\"email\":\"[email protected]\", \"password\":\"mySecret\"}", sw.toString() );
}

The marshalled data is in XML format, not JSON format. How can I instruct the JAXB reference implementation to output JSON?

like image 547
Abdull Avatar asked Dec 03 '22 14:12

Abdull


1 Answers

JAXB reference implementation does not support JSON, you need to add a package like Jackson or Moxy

Moxy

 //import org.eclipse.persistence.jaxb.JAXBContextProperties;
 
 Map<String, Object> properties = new HashMap<String, Object>(2);
 properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
 properties.put(JAXBContextProperties.JSON_INCLUDE_ROOT, false);
 JAXBContext jc = JAXBContext.newInstance(new Class[] {User.class}, properties);

 Marshaller marshaller = jc.createMarshaller();
 marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
 marshaller.marshal(user, System.out);

See example here

Jackson

//import org.codehaus.jackson.map.AnnotationIntrospector;
//import org.codehaus.jackson.map.ObjectMapper;
//import org.codehaus.jackson.xc.JaxbAnnotationIntrospector;

ObjectMapper mapper = new ObjectMapper();  
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
mapper.setAnnotationIntrospector(introspector);
     
String result = mapper.writeValueAsString(user);

See example here

like image 131
pedrofb Avatar answered Dec 05 '22 03:12

pedrofb