關於使用JSONArray.fromObject()方法和引入net.sf.json包所須要的jar包支持

 

關於使用JSONArray.fromObject()方法和引入net.sf.json包所須要的jar包支持。
net.sf.json的下載地址
http://www.java2s.com/Code/Jar/j/json-lib.htm
本次選擇 json-lib-2.3-jdk15.jar 版本
最新的是2.4的版本,本次使用的是 json-lib-2.3-jdk15.jar;
json-lib還須要如下依賴包:
jakarta commons-lang 2.5
jakarta commons-beanutils 1.8.0
jakarta commons-collections 3.2.1
jakarta commons-logging 1.1.1
ezmorph 1.0.6java

 

使用樣例:json

String json = "[{'day1':'work','day2':26},{'day1':123,'day2':26}]"; 
JSONArray jsonArray = JSONArray.fromObject(json);

 

實際使用:數組

String allWaterArrayString = req.getParameter("allWaterArrayString");
JSONArray allWaterArray = JSONArray.fromObject(allWaterArrayString);
int count = 0;
List<MonitorAutoEntity> gasList = JSONArray.toList(allWaterArray, new MonitorAutoEntity(), new JsonConfig());
for (MonitorAutoEntity monitorAutoEntity : gasList) {
  monitorAutoEntity.setPublishstatus("2");
  count += this.monitoringInfoService.updateMonitorWaterInfo(monitorAutoEntity);
}

 


下面引自http://blog.csdn.net/chenaschen/article/details/41543421內容,方便記錄。
1、字符串與json
字符串格式: 函數

static String json = 「[{‘day1’:’work’,’day2’:26},{‘day1’:123,’day2’:26}]」;

 

轉換爲json數組 this

JSONArray jsonArray = JSONArray.fromObject(json);

 

單個json對象轉換 spa

static String jobj = {‘day1’: 1, ‘day2’: 2};

 

[java] view plain copy.net

JSONObject obj = JSONObject.fromObject(jobj); 

 

json轉換爲Java beancode

JSONObject jsonObject = JSONObject.fromObject(new JsonBean()); 

 

List 轉換成json(Map也能夠)htm

List list = new ArrayList(); 
JsonBean2 jb1 = new JsonBean2(); 
jb1.setCol(1); 
jb1.setRow(1); 
jb1.setValue("xx");

JsonBean2 jb2 = new JsonBean2(); 
jb2.setCol(2); 
jb2.setRow(2); 
jb2.setValue("");

list.add(jb1); 
list.add(jb2); 
JSONArray ja = JSONArray.fromObject(list); 

 

2、遍歷Json數組對象

輸出每一個成員

for(int i=0; i<jsonArray.size(); i++){ 
  System.out.println(jsonArray.get(i)); 
}

 

獲取每一個成員的key及value

JSONObject obj = (JSONObject) jsonArray.get(i); 
Iterator it = obj.keys(); 
while (it.hasNext()) { 
  String key = it.next().toString(); 
  System.out.println("key ----- "+key); 
  System.out.println("value ----- "+obj.get(key)); 
} 

 

3、修改、添加、刪除成員

修改
涉及到修改json成員的不多,若是真的要修改的話,我的建議轉爲字符串而後用replaceAll這個函數進行修改,若是你有更好的建議歡迎給評論。
增長

JSONObject obj2 = new JSONObject(); 
obj2.put("day1", "study"); 
obj2.put("day2", "2"); 
jsonArray.add(obj2);


刪除

jsonArray.remove(index); 
jsonArray.subList(fromIndex, toIndex) 

 



尊重原創,原文:https://blog.csdn.net/y562363753/article/details/76704975/ 

相關文章
相關標籤/搜索