json
来源:互联网 发布:手机在线网页聊天源码 编辑:程序博客网 时间:2024/06/01 12:40
在Java中要想方便的操作json首先要引入json的jar包,如json-lib-2.4-jdk15.jar
下面是一些常用的方法:
Map<String,String> map1 = newHashMap<String,String>();
map1.put("username","liuwei");
map1.put("psw", "123");
//Map转换为json对象
//方法一:转换为带有key值的json对象
JSONObject json0 = new JSONObject();
json0.put("mapJson=", map1);
System.out.println("json0="+json0);
//方法二:转化为不带有key值的json对象
JSONObject json1 = JSONObject.fromObject(map1);
//Map对象转化为json数组
JSONArray mapArr = JSONArray.fromObject(map1);
ListMap转化为json对象
//方法一:转化为没有key值的json对象
List<Map<String,String>> listMap = newArrayList<Map<String,String>>();
Map<String,String> map2 = newHashMap<String,String>();
map2.put("username", "zhangsan");
map2.put("psw", "46732");
listMap.add(map1);
listMap.add(map2);
JSONArray jsonArray =JSONArray.fromObject(listMap);
//f方法二:转化为带有key值的json对象
JSONObject json5 = new JSONObject();
json5.put("1", listMap);
json数组转化为带有key值的json对象
JSONObject jsonobj2 = new JSONObject();
jsonobj2.put("newuser", jsonArray);
jsonobj2.put("otheruser", jsonArray2);
json对象转换为json字符串
String jsonstr = jsonobj2.toString();
json字符串转换为json对象
JSONObject jsonObj = JSONObject.fromObject(jsonstr);
获取json对象的key获取属性值,并可以转化为map
Map<String,String> map = new HashMap<String,String>();
map.put("username",jsonObjOne.getString("username"));
map.put("psw", jsonObjOne.getString("psw"));
json数组转化为ListMap
List<Map<String,String>> list4 = newArrayList<Map<String,String>>();
for(int i = 0;i < jsonArr2.size();i++){
JSONObject jsonObjOne = jsonArr2.getJSONObject(i);
Map<String,String> map = new HashMap<String,String>();
map.put("username", jsonObjOne.getString("username"));
map.put("psw", jsonObjOne.getString("psw"));
list4.add(map);
}
- Json
- JSON
- JSON
- JSON
- json
- JSON
- JSON
- json
- Json
- json
- JSON
- json
- json
- JSON
- json
- JSON
- JSON
- json
- Mac下安装graphviz
- 基于Kubernetes构建Docker集群管理详解
- navisworks ViewControl在WPF中的使用
- mui开发APP教程之仿天猫支付弹出自定义框
- .axf 转化 .bin文件 的方法
- json
- 简单的例子理解java线程的生命周期
- 数据结构之线性表
- 读书笔记_Effective_C++_条款十一:在operator=中处理自我赋值
- 网格模型obj文件及其纹理解析
- 欢迎使用CSDN-markdown编辑器
- vue2.0学习——组件开发01
- HDU 3709 Balanced Number(数位DP)
- 修改jenkins主目录与cp参数a使用