在java中操作json数据,需要引入相应的jar
1.java中解析json(具体看获取的json格式,解析json数组还是json对象)
//{"age":29,"name":"james"}
response.setContentType( "application/json");
//服务器响应的类型
String jsonString = request.getParameter( "testJsonString" ); //获取传过来的json字符串
JSONObject jsonobj = JSONObject. fromObject(jsonString); //把json格式的字符串转化为json对象
System.out.println("name:" +jsonobj.getString("name")+ ",age:"+jsonobj.getInt("age" ));
输入结果:name:james,age:29
(2)把json数组形式的字符串转化为json数组,再解析出来
//[{"name":"olay","age":21},{"name":"james","age":22},{"name":"kobe","age":34}]
response.setContentType("application/json");
//服务器响应的类型
String jsondata = request.getParameter( "testJsonArray"); //获取传过来的json字符串
System. out.println(jsondata); //[{"name":"olay","age":21},{"name":"james","age":22},{"name":"kobe","age":34}]
JSONArray jsonArray = JSONArray. fromObject(jsondata); //转化为json数组
for(int i=0;i<jsonArray.size();i++){
//遍历json数组
JSONObject obj = JSONObject. fromObject(jsonArray.get(i));
//转化为json对象
System.out.println("name:" +obj.getString("name")+ ",age:"+obj.getInt("age" ));
}
(3)解析成javabean
//{"age":29,"name":"james"}
response.setContentType( "application/json");
//服务器响应的类型
String jsonString = request.getParameter( "testJsonString" ); //获取传过来的json字符串
JSONObject jsonobj = JSONObject. fromObject(jsonString); //把json格式的字符串转化为json对象
User u = new User();
u=(User)JSONObject. toBean(jsonobj,
User. class); //把json对象转化为javabean
System. out .println("javabean:" +u.getName()+ ","+u.getAge()); //javabean:james,29
2.java中创建json
(1)java字符串转为为json对象
String jsonString = "{\"name\":\"olay\",\"age\":100}" ;
JSONObject j = JSONObject.fromObject(jsonString);
//java字符串转为为json对象
System. out.println(j); //{"name":"olay","age":100}
(2)java对象转化为json对象
User user1 = new User();
user1.setName( "james");
user1.setAge(29);
JSONObject obj =JSONObject .fromObject(user1);
//转化为json对象
System. out.println(obj);
//{"age":29,"name":"james"}
(3)java中lst集合转为为json数组
User user1 = new User();
user1.setName( "james");
user1.setAge(29);
User user2 = new User();
user2.setName( "olay");
user2.setAge(22);
List list = new ArrayList();
list.add(user1);
list.add(user2);
JSONArray arr = JSONArray.fromObject(list);
//lst集合转为为json数组
System. out.println(arr); //[{"age":29,"name":"james"},{"age":22,"name":"olay"}]
(4)java中Map集合转化为json二位数组
Student student = new Student();
student.setName( "张三");
student.setAge(15);
student.setSex( "男");
Teacher teacher = new Teacher();
teacher.setName( "梨花");
teacher.setAge(29);
teacher.setSex( "女");
Map map
= new HashMap();
map.put("student",
student);
map.put("teacher",
teacher);
JSONArray arrMap = JSONArray.fromObject(map);
//Map集合转化为json二位数组
System. out.println(arrMap);
//[{"student":{"age":15,"name":"张三","sex":"男"},"teacher":{"age":29,"name":"梨花","sex":"女"}}]