一个简单的json解析代码。
首先把数据库对应的实体类写一下,然后写接口,再进行操作。
我这里用的是mybatis-plus。json有三层,多层的话套娃就行,很简单。
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.niit.mybatisplus.dao.PositionMapper;
import com.niit.mybatisplus.pojo.Position;
import com.niit.mybatisplus.service.impl.PositionServiceImpl;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.*;
/**
* @author 余天
* @ClassName json6.java
* @Description 1
* @createTime 2021-09-02 14:43
**/
@SpringBootTest
public class json6 {
@Autowired
PositionMapper positionMapper;
@Test
public void jsontosql() {
String path = "json文件路径";
String s = readJsonFile(path);
JSONObject jobj = JSON.parseObject(s);
JSONArray student = jobj.getJSONArray("zhiwei");//构建JSONArray数组
for (int i = 0 ; i < student.size();i++){ // 第一层
Position position = new Position();
JSONObject key = (JSONObject)student.get(i);
String code= (String) key.get("value");
String name= (String) key.get("label");
position.setCode(code);
position.setName(name);
System.out.println("第一层:"+position.getCode()+":"+position.getName());
positionMapper.insert(position);
JSONArray sons = key.getJSONArray("children");
if(sons!=null) {
for (int j = 0; j < sons.size(); j++) { // 第二层
Position son = new Position();
JSONObject Sonkey = (JSONObject) sons.get(j);
String sonCode = (String) Sonkey.get("value");
String sonName = (String) Sonkey.get("label");
son.setCode(sonCode);
son.setName(sonName);
son.setParentCode(code);
son.setParentName(name);
System.out.println("第二层:" + son.getCode() + ":" + son.getName());
positionMapper.insert(son);
JSONArray gsons = Sonkey.getJSONArray("children");
if(gsons!=null){
for (int k = 0; k < gsons.size(); k++) { // 第三层
Position gson = new Position();
JSONObject gsonkey = (JSONObject) gsons.get(k);
String gsonCode = (String) gsonkey.get("value");
String gsonName = (String) gsonkey.get("label");
gson.setCode(gsonCode);
gson.setName(gsonName);
gson.setParentCode(sonCode);
gson.setParentName(sonName);
System.out.println("第三层:" + gson.getCode() + ":" + gson.getName());
positionMapper.insert(gson);
}
}
}
}
}
}
public static String readJsonFile(String fileName) {
String jsonStr = "";
try {
File jsonFile = new File(fileName);
FileReader fileReader = new FileReader(jsonFile);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
fileReader.close();
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}