Fastjson 实现类导出json文件
Posted zolty
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Fastjson 实现类导出json文件相关的知识,希望对你有一定的参考价值。
0.背景
利用fastjson实现 java类导出json文件
依赖:
<!-- 阿里JSON解析器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
1.定义类
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Map;
public class MqttJson {
private int[] dev_ids;
private String msg_type;
private Map<String,Integer> control_command;
public int[] getDev_ids() {
return dev_ids;
}
public void setDev_ids(int[] dev_ids) {
this.dev_ids = dev_ids;
}
public String getMsg_type() {
return msg_type;
}
public void setMsg_type(String msg_type) {
this.msg_type = msg_type;
}
public Map<String, Integer> getControl_command() {
return control_command;
}
public void setControl_command(Map<String, Integer> control_command) {
this.control_command = control_command;
}
//导出函数
public static void save(String filename,String json) throws IOException {
OutputStreamWriter osw=new OutputStreamWriter(new FileOutputStream(filename), StandardCharsets.UTF_8);
osw.write(json);
osw.flush();
osw.close();
}
}
2.赋值以及转化导出
public void class2json()throws IOException {
MqttJson mqttJson = new MqttJson();
mqttJson.setDev_ids(String2int(ids));
mqttJson.setMsg_type("CONTROLCOMMAND");
Map<String, Integer> contol_comand = new HashMap<String, Integer>(){
{
put("stack_flag", 1);
put("record_log_flag", 1);
}
};
mqttJson.setControl_command(contol_comand);
String json= JSON.toJSONString(mqttJson);
mqttJson.save("D://CONTROL_COMMAND.json",json);
}
3.JSON效果
{
"control_command":{"record_log_flag":1,"stack_flag":1},
"dev_ids":[1,2,3,4,5],
"msg_type":"CONTROLCOMMAND"
}
以上是关于Fastjson 实现类导出json文件的主要内容,如果未能解决你的问题,请参考以下文章
spring boot :使用fastJson解析json数据