How to convert an xml into a json using gson library

Tags: , , ,



I have to convert a XML using gson library into a JSON

i havenĀ“t found how to do it using gson library(java)

Answer

You could use Jackson to do this:

import these libraries:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.1</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.11.1</version>
</dependency>

then do this in your class:

    public class Example {
        private String name;
        private int number;
    }
    Example example = new XmlMapper().readValue(xml, Example.class);
    String json = new ObjectMapper().writeValueAsString(example);



Source: stackoverflow