Jar包
gson-2.6.2.jar
文件结构
- project
- src
- Data.java
- Entity.java
- Test.java
- src
原Json
inJsonTest.json
{
"rst": "0",
"msg": "ok",
"data": {
"id": "1",
"name": "firstBug",
"time": "2019-01-02 20:20:30",
"type": "ERROR",
"content": "It was a pure accident."
}
}
目标Json
outJsonTest.json
"data": {
"id": "1",
"name": "firstBug",
"time": "2019-01-02 20:20:30",
"type": "ERROR",
"content": "It was a pure accident."
}
代码
Data.java
public class Data {
private String id;
private String name;
private String type;
private String time;
private String content;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
Entity .java
public class Entity {
private String rst;
private String msg;
private Data data;
public String getRst() {
return rst;
}
public void setRst(String rst) {
this.rst = rst;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Data getData() {
return data;
}
public void setData(Data data) {
this.data = data;
}
}
Test.java
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.*;
import java.util.*;
public class Test {
public static void main(String[] args) throws IOException {
try {
//原Json文件
File infile = new File("D:"+File.separator+"download"+File.separator+"document"+File.separator+"inJsonTest.json");
//目标Json文件
File outfile = new File("D:"+File.separator+"download"+File.separator+"document"+File.separator+"outJsonTest.json");
InputStream in = new FileInputStream(infile);
OutputStream out = new FileOutputStream(outfile);
byte[] buf =new byte[in.available()];
HashMap<String,Object> hashMap = new HashMap<>();
in.read(buf);
//将Json转换成实体对象
Entity entity = new Gson().fromJson(new String(buf), Entity.class);
//只获取所需要的元素
hashMap.put("data",entity.getData());
//格式化json
Gson gson = new GsonBuilder().setPrettyPrinting().create();
buf = gson.toJson(hashMap).getBytes();
if(!outfile.exists()){
outfile.createNewFile();
}
out.write(buf);
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}