【FastJson】转换处理JsonArrays、JsonArray文件转换为txt文件



转换处理JsonLine、JsonArray、JsonArrays文件转换为txt文件

Fastjson当需要处理超大JSON文本时,需要Stream API,在fastjson-1.1.32版本中开始提供Stream API。

一、JsonLine文件转化

Json文件样式:
在这里插入图片描述
案例:

  • 下面是一段招聘信息的JsonLine数据文件,对其进行相应的解析
    在这里插入图片描述
package jsonLine.Example;

public class EmployInfo {
    
    
    // 定义属性
    private String id;                   // id
    private String company_name;      // 公司名称
    private String ceduLevel_name;    // 学历
    private String emplType;          // 工种
    private String jobName;           // 职称
    private String salary;            // 薪资
    private String createDate;        // 发布时间
    private String endDate;           // 截止时间
    private String city_code;         // 城市编码
    private String companySize;      // 公司规模
    private String welfare;           // 福利
    private String responsibility;     // 岗位职责
    private String place;             // 所处地区
    private String workingExp;        // 工作经验

    // 重写toString()
    @Override
    public String toString() {
    
    
        StringBuffer buf = new StringBuffer();
        buf.append(this.id).append(",");
        buf.append(this.company_name).append(",");
        buf.append(this.ceduLevel_name).append(",");
        buf.append(this.emplType).append(",");
        buf.append(this.jobName).append(",");
        buf.append(this.salary).append(",");
        buf.append(this.createDate).append(",");
        buf.append(this.endDate).append(",");
        buf.append(this.city_code).append(",");
        buf.append(this.companySize).append(",");
        buf.append(this.welfare).append(",");
        buf.append(this.responsibility).append(",");
        buf.append(this.place).append(",");
        buf.append(this.workingExp);
        return buf.toString();
    }

    // setter\getter
    // 省略

    public void set(String data, String data1, String data2, String data3, String data4, String data5, String data6, String data7, String data8, String data9, String data10, String data11, String data12, String data13) {
    
    
        this.id = data;
        this.company_name = data1;
        this.ceduLevel_name = data2;
        this.emplType = data3;
        this.jobName = data4;
        this.salary = data5;
        this.createDate = data6;
        this.endDate = data7;
        this.city_code = data8;
        this.companySize = data9;
        this.welfare = data10;
        this.responsibility = data11;
        this.place = data12;
        this.workingExp = data13;
    }
}

转换JsonLine:

  • 每读一行Json,先转换数据,将最后的","去除;然后将转换结果转为JsonObject对象,利用jsonObject.getString("属性名")来获取对应属性值,存入一个数组;然后通过自定义set(参数是属性们)方法进行赋值;之后通过封装Bean类的toString()方法作为结果写出,记住写出一条json(对象)要多加个"\n"换行符。
package jsonLine.Example;

import com.alibaba.fastjson.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

public class parse {
    
    
    public static void main(String[] args) {
    
    
        String str = "";
        String readPath = "G:\\Projects\\IdeaProject-C\\fastjson_demo\\src\\main\\java\\jsonLine\\data\\exploy.json";
        String writePath = "G:\\Projects\\IdeaProject-C\\fastjson_demo\\src\\main\\java\\jsonLine\\result\\result.txt";
        try {
    
    
            BufferedReader reader = new BufferedReader(new FileReader(readPath));
            BufferedWriter writer = new BufferedWriter(new FileWriter(writePath));
            while ((str = reader.readLine()) != null) {
    
    
                EmployInfo employInfo = new EmployInfo();
                //System.out.println(str);
                str = str.toString().substring(0,str.length()-1); // 去除逗号
                //System.out.println(str);
                JSONObject jsonObject = JSONObject.parseObject(str);
                //System.out.println(jsonObject);
                String[] datas = new String[14];
                datas[0] = jsonObject.getString("id");
                datas[1] = jsonObject.getString("company_name");
                datas[2] = jsonObject.getString("eduLevel_name");
                datas[3] = jsonObject.getString("emplType");
                datas[4] = jsonObject.getString("jobName");
                datas[5] = jsonObject.getString("salary");
                datas[6] = jsonObject.getString("createDate");
                datas[7] = jsonObject.getString("endDate");
                datas[8] = jsonObject.getString("city_code");
                datas[9] = jsonObject.getString("companySize");
                datas[10] = jsonObject.getString("welfare");
                datas[11] = jsonObject.getString("responsibility");
                datas[12] = jsonObject.getString("place");
                datas[13] = jsonObject.getString("workingExp");
//                for (String s : datas) {     // 去空
//                    if (s.equals("") || s == null) {
    
    
//                        return;
//                    }
//                }
                employInfo.set(datas[0],datas[1],datas[2],datas[3],datas[4],datas[5],datas[6],datas[7],datas[8],datas[9],datas[10],datas[11],datas[12],datas[13]);
                System.out.println(employInfo.toString());
                writer.write(employInfo.toString());
                writer.write("\n");
                writer.flush();
            }
            // 关闭流资源
            reader.close();
            writer.close();
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

返回顶部


二、JsonArray文件转化

Json文件样式:
在这里插入图片描述

如果你的JSON格式是一个巨大的JSON数组,有很多元素(每一个元素都是一个json格式数据),则先调用startArray,然后挨个写入对象,然后调用endArray。

JSONWriter writer = new JSONWriter(new FileWriter("/tmp/huge.json"));
writer.startArray();
for (int i = 0; i < 1000 * 1000; ++i) {
    
    
      writer.writeValue(new VO());
}
writer.endArray();
writer.close();

案例:

  • 下面是一个有关豆瓣电影排名的推荐json文件,利用fastjson进行解析
    在这里插入图片描述

    扫描二维码关注公众号,回复: 12870854 查看本文章
  • 针对Json文件的内容进行Bean类的封装 — 属性重写toString()setter()\getter()

package jsonArray.Example;

public class movies {
    
    

    // 属性
    private String rating;
    private int rank;
    private String cover_url;
    private String is_playable;
    private String id;
    private String types;
    private String regions;
    private String title;
    private String url;
    private String release_date;
    private int actor_count;
    private int vote_count;
    private String score;
    private String actors;
    private String is_watched;

    // 重写toString()
    @Override
    public String toString() {
    
    
        return rating + "\t" +
                rank + "\t" +
                cover_url + "\t" +
                is_playable + "\t" +
                id + "\t" +
                types + "\t" +
                regions + "\t" +
                title + "\t" +
                url + "\t" +
                release_date + "\t" +
                actor_count + "\t" +
                vote_count + "\t" +
                score + "\t" +
                actors + "\t" +
                is_watched;
    }

    // 自定义设置属性值
    public void set(String rating, int rank, String cover_url, String is_playable, String id, String types, String regions, String title,
                    String url, String release_date, int actor_count, int vote_count, String score, String actors, String is_watched) {
    
    
        this.rating = rating;
        this.rank = rank;
        this.cover_url = cover_url;
        this.is_playable = is_playable;
        this.id = id;
        this.types = types;
        this.regions = regions;
        this.title = title;
        this.url = url;
        this.release_date = release_date;
        this.actor_count = actor_count;
        this.vote_count = vote_count;
        this.score = score;
        this.actors = actors;
        this.is_watched = is_watched;
    }

    // setter、getter
    省略私有属性的setter、getter方法
}

使用startArray()\endArray()进行Json文件解析转换

package jsonArray.Example;

import com.alibaba.fastjson.JSONReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

public class parse {
    
    
    public static void main(String[] args) throws Exception {
    
    
         // 如果你的JSON格式是一个巨大的JSON数组,有很多元素,则先调用startArray,然后挨个写入对象,然后调用endArray。
        JSONReader reader = new JSONReader(new FileReader("G:\\Projects\\IdeaProject-C\\fastjson_demo\\src\\main\\java\\jsonArray\\data\\movie.json"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("G:\\Projects\\IdeaProject-C\\fastjson_demo\\src\\main\\java\\jsonArray\\result\\result.txt"));
        // 开始读取
        reader.startArray();
        // 循环读取文件信息
        while (reader.hasNext()) {
    
    
            // 将json数组的每一个对象转换为封装的Bean对象
            movies movie = reader.readObject(movies.class);
            // 将转换的对象输出
            bw.write(movie.toString());
            // 每写一个对象,换行 --- 一个对象的内容作为一条数据
            bw.write("\n");
            // 流刷新,方式数据残余
            bw.flush();
        }
        // 结束读取
        reader.endArray();
        // 关闭流
        bw.close();
    }
}

在这里插入图片描述

返回顶部


三、JsonArays文件转化

Json文件样式:
在这里插入图片描述
案例:

  • 下面是一个有关豆瓣电影排名的推荐json文件,利用fastjson进行解析
    在这里插入图片描述

超大JSON多个数组:

  • 与JsonArray不同的是,JsonArrays的结构是多个数组形式的json文件,在处理的时候,本人采取的方式是将JsonArrays文件中的部分内容进行更改,时期变成JsonArray的结构形式,然后再使用startArray()、endArray()进行挨个写入对象

  • 通过观察两者的格式可以发现,如果将JsonArrays中的 ][ 替换成 ,那么就变成了JsonArray的格式了。

package jsonArrays.Example;

import java.io.*;

public class parse {
    
    
    public static void main(String[] args) {
    
    
        // 读取json文件转为jsonArray文件
        String jsonStr = "";
        String jsonFile = "G:\\Projects\\IdeaProject-C\\fastjson_demo\\src\\main\\java\\jsonArrays\\data\\douban.json";
        String jsonFileout = "G:\\Projects\\IdeaProject-C\\fastjson_demo\\src\\main\\java\\jsonArrays\\result\\result.json";
        try {
    
    
            BufferedReader br = new BufferedReader(new FileReader(jsonFile));   // 定义文件输入流读取文件
            BufferedWriter bw = new BufferedWriter(new FileWriter(jsonFileout));// 定义文件输出流写入文件
            while ((jsonStr=br.readLine())!=null){
    
            // 每次读取一行数据
                jsonStr = jsonStr.replace("][",",");      // 对目标内容进行替换
                bw.write(jsonStr);                        // 写出到输出流
                bw.flush();                               // 刷新流
            }
            // 关闭流资源
            br.close();
            bw.close();
        } catch (Exception e){
    
    
            e.printStackTrace();
        }
    }
}

处理完后,可以用notepad++打开文件查看,查找 ][ ,按回车后没反应,说明原始的数据已经被修改。在这里插入图片描述
接下来的步骤就和JsonArray的处理方式相同了。

自定义封装Bean类:

package jsonArray;

public class movies {
    
    

    // 属性
    private String rating;
    private int rank;
    private String cover_url;
    private String is_playable;
    private String id;
    private String types;
    private String regions;
    private String title;
    private String url;
    private String release_date;
    private int actor_count;
    private int vote_count;
    private String score;
    private String actors;
    private String is_watched;

    // 重写toString()
    @Override
    public String toString() {
    
    
        return rating + "\t" +
                rank + "\t" +
                cover_url + "\t" +
                is_playable + "\t" +
                id + "\t" +
                types + "\t" +
                regions + "\t" +
                title + "\t" +
                url + "\t" +
                release_date + "\t" +
                actor_count + "\t" +
                vote_count + "\t" +
                score + "\t" +
                actors + "\t" +
                is_watched;
    }

    // 自定义设置属性值
    public void set(String rating, int rank, String cover_url, String is_playable, String id, String types, String regions, String title,
                    String url, String release_date, int actor_count, int vote_count, String score, String actors, String is_watched) {
    
    
        this.rating = rating;
        this.rank = rank;
        this.cover_url = cover_url;
        this.is_playable = is_playable;
        this.id = id;
        this.types = types;
        this.regions = regions;
        this.title = title;
        this.url = url;
        this.release_date = release_date;
        this.actor_count = actor_count;
        this.vote_count = vote_count;
        this.score = score;
        this.actors = actors;
        this.is_watched = is_watched;
    }

    // setter、getter
    省略私有属性的setter、getter方法
}

使用fastjson对文件进行解析,转换为txt文件

package jsonArrays.Example;

import com.alibaba.fastjson.JSONReader;
import jsonArray.Example.movies;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;

public class parse_final {
    
    
    public static void main(String[] args) {
    
    
        try {
    
    
            // 如果你的JSON格式是一个巨大的JSON数组,有很多元素,则先调用startArray,然后挨个写入对象,然后调用endArray。
            JSONReader reader = new JSONReader(new FileReader("G:\\Projects\\IdeaProject-C\\fastjson_demo\\src\\main\\java\\jsonArrays\\result\\result.json"));
            BufferedWriter bw = new BufferedWriter(new FileWriter("G:\\Projects\\IdeaProject-C\\fastjson_demo\\src\\main\\java\\jsonArrays\\result\\result.txt"));
            // 开始读取
            reader.startArray();
            // 循环读取文件信息
            while (reader.hasNext()) {
    
    
                // 将json数组的每一个对象转换为封装的Bean对象
                jsonArray.Example.movies movie = reader.readObject(movies.class);
                // 将转换的对象输出
                bw.write(movie.toString());
                // 每写一个对象,换行 --- 一个对象的内容作为一条数据
                bw.write("\n");
                // 流刷新,方式数据残余
                bw.flush();
            }
            // 结束读取
            reader.endArray();
            // 关闭流
            bw.close();
        } catch (Exception e){
    
    
            e.printStackTrace();
        }
    }
}

在这里插入图片描述

返回顶部


猜你喜欢

转载自blog.csdn.net/qq_45797116/article/details/114658755