TableA、TableB 是根据json数据创建的实体类 建议将json数据放到json.cn
里面格式化
json-lib是一个java类库,提供将Java对象,包括beans, maps, collections, java arrays and XML等转换成JSON,或者反向转换的功能。
import net.sf.json.*; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; public class findElectSet { /* * 取出文件内容,填充对象 */ public List<TableA> writeFile(String path) { List<TableA> tableAS = new ArrayList<>(); String sets = ReadFile(path);//获得json文件的内容 JSONObject jsonObject = JSONObject.fromObject(sets);//格式化成json对象 Object data = jsonObject.get("data"); JSONObject jsonObject1 = JSONObject.fromObject(data); String list = jsonObject1.getString("list"); JSONArray jsonArray = JSONArray.fromObject(list); List<TableA> tableAList = new ArrayList<>(); for (Object o : jsonArray) { JSONObject jo = JSONObject.fromObject(o); TableA tableA = new TableA(); tableA.setId(jo.getString("id")); tableA.setZbbmText(jo.getString("zbbmText")); tableA.setCreateDate(jo.getString("createDate")); tableA.setTopic(jo.getString("topic")); tableA.setCreateUserText(jo.getString("createUserText")); tableA.setWh(jo.getString("wh")); tableA.setFwrq(jo.getString("fwrq")); List<TableB> tableBList = new ArrayList<>(); String attlist = jo.getString("attlist"); JSONArray jsonArray1 = JSONArray.fromObject(attlist); for (Object jsonArr1 : jsonArray1) { JSONObject j = JSONObject.fromObject(jsonArr1); TableB tableB = new TableB(); tableB.setContentId(j.getString("contentId")); tableB.setDurl(j.getString("durl")); tableB.setTopic(j.getString("topic")); tableB.setType(j.getString("type")); tableBList.add(tableB); } tableA.setAttlist(tableBList); tableAList.add(tableA); } return tableAList; } //读文件,返回字符串 public String ReadFile(String path) { StringBuffer strBuf = new StringBuffer(); try { URL url = new URL(path); URLConnection conn = url.openConnection(); BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8")); String line = null; while((line = reader.readLine()) != null) { strBuf.append(line + " "); } reader.close(); } catch (MalformedURLException e) { System.out.println(); } catch (IOException e) { System.out.println(e); } return strBuf.toString(); } }
@SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); findElectSet f=new findElectSet(); List<TableA> tableAS = f.writeFile("http://XXXXXXXXXXXXXXXXX"); System.out.println(tableAS.toString()); } }