简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM