Skip to content
Advertisement

How to convert an xml into a json using gson library

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

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

Advertisement

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);

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement