关于java读取转换json文件问题

 我们这里使用fastjosn

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.68</version>
        </dependency>

_code: 



import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;

import javax.sound.midi.Soundbank;
import java.io.*;
import java.util.List;
import java.util.Map;


/**
 * @Author s.o.n.g
 * @create 2022/8/30
 */
public class ReadLocalJsonFileDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("C:\\Users\\Administrator\\Desktop\\XX.json");
        readerMethod(file);

    }
    private static <error> void readerMethod(File file) throws IOException {
        FileReader fileReader = new FileReader(file);
        Reader reader = new InputStreamReader(new FileInputStream(file), "Utf-8");
        int ch = 0;
        StringBuffer sb = new StringBuffer();
        while ((ch = reader.read()) != -1) {
            sb.append((char) ch);
        }
        fileReader.close();
        reader.close();
        String jsonStr = sb.toString();
        System.out.println(jsonStr);
        //如果是json是非数组类型的情况使用下面的转化
        try {
            System.out.println(JSONObject.parseObject(jsonStr));
            //这个地方可能会报错 看看是不是需要升级fastjson 或者 读取的json文件格式不对
        }catch (Exception  error){
            System.out.println(error);
        }

        //如果是json是数组转对象 下面
       /* JSONArray jsona =(JSONArray)JSONArray.parse(jsonStr);
        System.out.println(jsona);
        List<Map> list = JSONObject.parseArray(jsona.toJSONString(), Map.class);
        System.out.println(list);

        for(Map i:list){
            System.out.println(i.get("id"));
        }*/

    }
}


注意:

json 的格式要正确 

一般两种格式

一种是: String转JSONObject

这种格式 需要在最外层有一个{}括号 如果是一个对象的话不需要

一个以上需要 最外面加{}不然报错。

 

 

一种是:String转JSONArray 

这种格式需

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Arenaschi

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值