1. 程式人生 > >java json物件轉換

java json物件轉換

引入的jar包:

commons-beanutils-1.9.2.jar

commons-collections-3.2.1.jar

commons-lang-2.6.jar

commons-logging-1.2.jar

ezmorph-1.0.6.jar

json-lib-2.4-jdk15.jar

 

字串存json物件裡:

String content = "123";

String content2 = "456";

JSONObject jsonObj = new JSONObject();

jsonObj.put("a",content);

jsonObj.put("b",content2);

System.out.println(jsonObj);//輸出{"a":"123","b":"456"}

 

fwriter = new FileWriter(savefile);

fwriter.write(jsonObj.toString()); //把jsonObj轉成string型別 存到檔案中

fwriter.flush();

fwriter.close();

 

從json物件裡獲取字串

while ((lineTxt = br.readLine()) != null) {

System.out.println(lineTxt); //從檔案中讀出的內容

JSONObject json = JSONObject.fromObject(lineTxt); //轉jsonobject

System.out.println(json.get("I"));//獲取I導連

JSONArray arr = (JSONArray) json.get("I");;//獲取I導連 放到集合中

//List list = (List) json.get("I"); 同上

System.out.println(list.get(2) instanceof Integer); //true

}