unmarshalling nested objects from json

后端 未结 1 835
广开言路
广开言路 2021-01-23 03:49

I have incoming JSON strings and I need to unmarshall into JAXB annotated objects. I am using jettison to do this. JSON string looks like this:

{ 
  objectA :          


        
相关标签:
1条回答
  • 2021-01-23 04:16

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

    The JAXB mappings on your model appear to be correct. Below is sample code where I used your exact model as given in your questions with the JSON-binding available through EclipseLink MOXy:

    Demo

    package forum16365788;
    
    import java.io.File;
    import java.util.*;
    import javax.xml.bind.*;
    import org.eclipse.persistence.jaxb.JAXBContextProperties;
    
    public class Demo {
    
        public static void main(String[] args) throws Exception {
            Map<String, Object> properties = new HashMap<String, Object>(1);
            properties.put(JAXBContextProperties.MEDIA_TYPE, "application/json");
            JAXBContext jc = JAXBContext.newInstance(new Class[] {ObjectA.class}, properties);
    
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            File json = new File("src/forum16365788/input.json");
            ObjectA objectA = (ObjectA) unmarshaller.unmarshal(json);
    
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.marshal(objectA, System.out);
        }
    
    }
    

    input.json/Output

    Below is the JSON I used. The keys objectA and objectB should be quoted, you don't have this in your question.

    {
       "objectA" : {
          "propertyOne" : "some val",
          "propertyTwo" : "some other val",
          "objectB" : {
             "propertyA" : "some val",
             "propertyB" : true
          }
       }
    }
    

    For More Information

    • http://blog.bdoughan.com/2011/08/json-binding-with-eclipselink-moxy.html
    • http://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy-as-your.html
    0 讨论(0)
提交回复
热议问题