使用JSONObject將json檔案轉化成物件
阿新 • • 發佈:2019-02-12
使用JSONObject將json檔案轉化為物件,最主要的步驟就是:
1.將json檔案轉化為字串,這裡用到了檔案流的讀取
2.引入json-lib包,呼叫裡面的方法。
比較簡單,只當做一個記錄
1.貼出test1.js檔案
{ "province":[{"cityId":18,"cityName":"西安"},{"cityId":53,"cityName":"廣州"}] }
2.貼出實體類檔案
public class Province { private String cityId; private String cityName; publicString getCityId() { return cityId; } public void setCityId(String cityId) { this.cityId = cityId; } public String getCityName() { return cityName; } public void setCityName(String cityName) { this.cityName = cityName; } @Override public String toString() { return "Province{" + "cityId='" + cityId + '\'' + ", cityName='" + cityName + '\'' + '}'; } }
下面是主要的方法
public class Main { public static void main(String[] args)throws Exception { String s = fileRead(); JSONObject jsonObject = new使用JsonParseUtils呼叫的方法為:JSONObject().fromObject(s); List<Map<String, Object>> provinceList = JsonParseUtils.toList(jsonObject.get("province")); ArrayList<Province> provinces = new ArrayList<>(); for (Map<String, Object> stringObjectMap : provinceList) { Province province = new Province(); province.setCityId(stringObjectMap.get("cityId").toString()); province.setCityName(stringObjectMap.get("cityName").toString()); provinces.add(province); } for (Province province : provinces) { System.out.println(province); } } public static String fileRead() throws Exception { File file = new File("test.json");//定義一個file物件,用來初始化FileReader FileReader reader = new FileReader(file);//定義一個fileReader物件,用來初始化BufferedReader BufferedReader bReader = new BufferedReader(reader);//new一個BufferedReader物件,將檔案內容讀取到快取 StringBuilder sb = new StringBuilder();//定義一個字串快取,將字串存放快取中 String s = ""; while ((s =bReader.readLine()) != null) {//逐行讀取檔案內容,不讀取換行符和末尾的空格 sb.append(s + "\n");//將讀取的字串新增換行符後累加存放在快取中 System.out.println(s); } bReader.close(); String str = sb.toString(); System.out.println(str ); return str; }
/*** * 將物件轉換為List> * @param object * @return */ // 返回非實體型別(Map)的List public static List<Map<String, Object>> toList(Object object) { List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(); JSONArray jsonArray = JSONArray.fromObject(object); for (Object obj : jsonArray) { JSONObject jsonObject = (JSONObject) obj; Map<String, Object> map = new HashMap<String, Object>(); Iterator it = jsonObject.keys(); while (it.hasNext()) { String key = (String) it.next(); Object value = jsonObject.get(key); map.put((String) key, value); } list.add(map); } return list; }
這裡我就不做過多的說明了,總之思路就是:new一個JsonObject物件,將讀取的檔案流String轉化為jJSONObject,然後new一個JSONArray物件,將object轉化為陣列物件,將陣列以鍵值對的方式放在map中,然後將map設定到物件中。
so easy!!!