Marshall/Unmarshall a JSON to a Java class using JAXB

前端 未结 3 1082
夕颜
夕颜 2020-12-11 11:42

I am successfully marshaling a POJO into JSON using JAX-RS and JAXB annotations.

The problem is that when I am trying to use the same for un-marshalling my request i

3条回答
  •  -上瘾入骨i
    2020-12-11 12:01

    Marshalling to XML is easy, but it took me a while to figure out how to marshall to JSON. Pretty simple after you find the solution though.

    public static String marshalToXml( Object o ) throws JAXBException {
    
        StringWriter writer = new StringWriter();
        Marshaller marshaller = JAXBContext.newInstance( o.getClass() ).createMarshaller();
        marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
        marshaller.marshal( o, writer );
        return writer.toString();
    }
    
    public static String marshalToJson( Object o ) throws JAXBException {
    
        StringWriter writer = new StringWriter();
        JAXBContext context = JSONJAXBContext.newInstance( o.getClass() );
    
        Marshaller m = context.createMarshaller();
        JSONMarshaller marshaller = JSONJAXBContext.getJSONMarshaller( m );
        marshaller.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
        marshaller.marshallToJSON( o, writer );
        return writer.toString();
    }
    

提交回复
热议问题