首先导入核心包fastJson和commons-io包
<!-- fastJson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
我的json数据是放在resources下
核心代码
package com.shengxun.service.impl;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.shengxun.domian.CmpNo;
import org.apache.commons.io.FileUtils;
import org.springframework.util.ResourceUtils;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class JsonData {
public static List<CmpNo> jsonDataString(){
List<CmpNo> cmpNos = new ArrayList<CmpNo>();
try {
String jsonData = FileUtils.readFileToString(ResourceUtils.
getFile("classpath:cmp2.json"), Charset.forName("UTF-8"));
JSONObject jsonObject = JSONObject.parseObject(jsonData);
JSONArray jsonArray = jsonObject.getJSONArray("rows");
for (int i = 0; i < jsonArray.size(); i++) {
CmpNo cmpNo = new CmpNo();
JSONArray jsonArray1 = jsonArray.getJSONArray(i);
cmpNo.setId(jsonArray1.getInteger(0));
cmpNo.setName(jsonArray1.getString(1));
cmpNo.setType(jsonArray1.getString(2));
cmpNo.setItype(jsonArray1.getInteger(3));
cmpNos.add(cmpNo);
}
} catch (IOException e) {
e.printStackTrace();
}
return cmpNos;
}
public static void main(String[] args){
System.out.println(jsonDataString().size());
}
}
之前用springboot处理json数据感觉不太清晰,后来又重新写了一下,加了swagger,lomback简化开发;
需要的同学请移步github: https://github.com/Alex67gg/json2data;
有不足指出请多多指教。