关于使用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.6

 

使用样例:

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内容,方便记录。
一、字符串与json
字符串格式:

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

 

转换为json数组

JSONArray jsonArray = JSONArray.fromObject(json);

 

单个json对象转换

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

 

[java] view plain copy

JSONObject obj = JSONObject.fromObject(jobj); 

 

json转换为Java bean

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

 

List 转换成json(Map也可以)

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); 

 

二、遍历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)); 
} 

 

三、修改、添加、删除成员

修改
涉及到修改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/ 

 

posted @ 2019-01-30 11:40  花生福  阅读(29232)  评论(1编辑  收藏  举报