2
respostas

JAXB Serialização JSON

Professor, É possível mudar o formato de XML para JSON utilizando JAXB, onde o código não seja tão extenso quanto o abaixo? Exemplo:

Student st = new Student();
        st.setName("JavaInterviewPoint");
        st.setAge("11");
        st.setId(12);
        try 
        {
            //Create jaxbContext
            JAXBContext jaxbContext = JAXBContext.newInstance(Student.class);
            //Getting Marshaller object
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            //Setting Marshaller MediaType to json
            jaxbMarshaller.setProperty("eclipselink.media-type", "application/json");
            //set it to true for printing the root element
            jaxbMarshaller.setProperty(MarshallerProperties.JSON_INCLUDE_ROOT, true);
            //set it to true for producing a formatted output
            jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            //printing the json in the console
            jaxbMarshaller.marshal(st, System.out);
        } 
        catch (JAXBException e) 
        {
            e.printStackTrace();
        }
2 respostas

Opa Gleyson, ainda não... essa é uma spec que está prevista para ter sua implementação vinda no java ee 8.. Eu não usaria o projeto do eclipse link, usaria um GSON da vida e geraria meu json de boa.

Obrigado professor ...

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software