public class Test {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws JSONException{
// TODO code application logic here.
//已有Json格式字符串{"id":"10001","name":"肉类","menus":[{"name":"牛肉","price":"30.00"},{"name":"羊肉","price":"20.00"}]}
//需求是将牛肉的price改为50.00
String json="{\"id\":\"10001\",\"name\":\"肉类\",\"menus\":[{\"name\":\"牛肉\",\"price\":\"30.00\"},{\"name\":\"羊肉\",\"price\":\"20.00\"}]}";
System.out.println("1. "+json);
JSONObject kindJson=new JSONObject(json);//将string转为jsonobject
String menuJson=kindJson.getString("menus");//获取到menus
JSONArray menus=new JSONArray(menuJson);//再将menuJson转为jsonarray
System.out.println("2. "+menus);
JSONObject beefJson= menus.getJSONObject(0);//根据下标0(类似数组)获取牛肉的json对象
beefJson.put("price", "50.00");//直接提交price的key,如果该key存在则替换value
menus.put(0, beefJson);//覆盖掉原来的值
System.out.println("3. "+beefJson);
System.out.println("4. "+menus);//替换完后打印查看
kindJson.put("menus", menus);//再将menus覆盖
json=kindJson.toString();//赋值
System.out.println("5. "+json);//替换完成
}
}
执行结果:
可见最后json字符串中的值被修改了,但是字段的顺序却发生了变化,因为JsonObject是用HashMap来存储的,
并不是按顺序进行存储,如果有这个需求的话可以自定义JsonObject,用有序的LinkedHashMap代替HashMap。
之前用的是使用replace进行直接替换,但是不会准确替换掉目标值,这里用的是将json字符串转换为json的对象,
然后逐步将需要修改的对象取出来,利用put将原来的值覆盖完后再逐步提交回去,这样比较准确。
第一次写文章,如有误,请指点 感谢!