Loading

【转】java实现xml转json

java实现xml转json(超简单方法)

首先是创建Maven项目,打开pom.xml配置文件,添加依赖如下:(只需要两个依赖)

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.11.0</version>
        </dependency>

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20220320</version>
        </dependency>
import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.json.JSONTokener;
import org.json.XML;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.applet.Main;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Properties;


@RestController()
@RequestMapping("/api")
public class ApiController {

    @Value("${filedir}")
    private  String filedir;

    @Value("${encode}")
    private  String encode;

    @GetMapping("/loadData")
    public String loadData() {
        try {
            return getJson(filedir, encode);
        } catch (Exception e) {
            return e.toString();
        }
    }

    private String getJson(String path, String encode) {
        try {
            InputStreamReader is = new InputStreamReader(new FileInputStream(path), encode);//读取xml
            String xml = IOUtils.toString(is);
            JSONObject json = XML.toJSONObject(xml);
            return json.toString();
        } catch (Exception e) {
            return e.toString();
        }
    }
}

 

posted @ 2022-07-21 10:13  眾尋  阅读(2756)  评论(0编辑  收藏  举报