Search code examples
javajsoncxfrs

JSON String to Object Mapping


I am having an JSON Response and what I need is to Map the corresponding JSON String to the particular Response class.Is there any tools or framework to do the same.

Response class is:

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "0")
@XmlAccessorType(XmlAccessType.FIELD)
public class Student {

     @XmlElement(name="0")
     private String firstName;
     @XmlElement(name="1")
     private String lastName;

     public String getFirstName() {
         return firstName;
     }
     public void setFirstName(String firstName) {
         this.firstName = firstName;
     }
     public String getLastName() {
         return lastName;
     }
     public void setLastName(String lastName) {
         this.lastName = lastName;
     }
}

Json Response String is {"0":{"0":"Rockey","1":"John"}}

I am using Apache CXF Framework with Jettison as the JSON Provider also uses JAXB to wire the data to low bandwidth clients.

Please make a note that I want to convert the number representations to corresponding fields.


Solution

  • Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

    Below is how you an support your use case with your Student class as annotated with EclipseLink JAXB (MOXy).

    Demo

    import java.io.StringReader;
    import java.util.*;
    import javax.xml.bind.*;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            Map<String, Object> properties = new HashMap<String, Object>(1);
            properties.put("eclipselink.media-type", "application/json");
            JAXBContext jc = JAXBContext.newInstance(new Class[] {Student.class}, properties);
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            StringReader json = new StringReader("{\"0\":{\"0\":\"Rockey\",\"1\":\"John\"}}");
            Student student = (Student) unmarshaller.unmarshal(json);
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(student, System.out);
        }
    
    }
    

    Output

    {
       "0" : {
          "0" : "Rockey",
          "1" : "John"
       }
    }
    

    jaxb.properties

    To use MOXy as your JAXB provider you need to include a file called jaxb.properties in the same package as your domain model with the following entry:

    javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
    

    MOXy and JAX-RS

    For JAX-RS applications you can leverage the MOXyJsonProvider class to enable JSON-binding (see: http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html).