Java操作Json

xiaoxiao2021-02-28  91

Json相关知识

简介:JSON(JavaScript Object Notation)是一种轻量级的数据交换格式。用法: 以”{“开始,以”}”结束。每个名称后跟一个”:”,多个名称对之间用”,”分割。数组是值的有序集合,一个数组以”[“开头,以”]”结尾。多个值之间用”,”分割。值可以是双引号括起来的字符串,数值,true,false,null,对象,或数组。这些结构可以嵌套。JSON和XML的比较 可读性:JSON和XML的可读性不相上下。可扩展性:XML天生有很好的扩展性,相对于XML,JSON的扩展性稍弱。解析难度:XML解析要考虑父、子节点,相对复杂,而JSON的解析难度几乎为0。总结:XML比较适合于标记文档,而JSON却更适合于数据交换处理。JSON对象:{"name":"gouwa","age":23}JSON数组:{"person":[{"name":"gousheng","age":24},{"name":"zhangsan","age":23}]}

Java操作Json的几种方式

Gson 构造方法Gson()Json字符串转对象或集合:fromJson(jsonStr,Class)集合或对象转Json字符串:toJson(JsonElement jsonElement) @Test public void testGson(){ Gson gson = new Gson(); String json = "{\"id\":1,\"sex\":\"男\",\"name\":\"gouwa\"}"; //Json字符串转对象 Student student = gson.fromJson(json, Student.class); System.out.println(student); //对象转Json字符串 String jsonstr = gson.toJson(student); System.out.println(jsonstr); //Json字符串转集合,注意改字符串的格式 String json02 = "[{\"id\":1,\"sex\":\"男\",\"name\":\"gouwa\"}," + "{\"id\":2,\"sex\":\"男\",\"name\":\"gousheng\"}]"; //获取集合类型 Type listType = new TypeToken<List<Student>>(){}.getType(); //Json字符串转集合 List<Student> list = gson.fromJson(json02, listType); for(Student s : list){ System.out.println(s.toString()); } //集合转Json字符串 List<Student> list02 = new ArrayList(); list02.add(new Student(1,"gouwa","男")); list02.add(new Student(2,"gousheng","男")); System.out.println(gson.toJson(list02)); }

2. JSONObject:json对象,{key:value}

构造方法JSONObject()、JSONObject(Map map)、JSONObject(String str)等普通方法:增加:accumulate(key,value)、put(key,value)删除:clear()、remove(key)查询:get(key)、isEmpty()、containsKey(key)、size()其他:fromObject(Object)对象转json,JSONObject转对象:toBean(JSONObject,Class)

@Test public void testJSONObject(){ JSONObject jsonObj = new JSONObject(); jsonObj.put("1", "一"); jsonObj.put("2", "二"); jsonObj.accumulate("3", "三"); System.out.println(jsonObj.toString());//{"1":"一","2":"二","3":"三"} System.out.println(jsonObj.containsKey("1"));//true //转为Set集合 Set entrySet = jsonObj.entrySet(); Iterator iterator = entrySet.iterator(); while(iterator.hasNext()){ System.out.println(iterator.next());//1=一 2=二 3=三 } System.out.println(jsonObj.size());//3 //Java对象转Json JSONObject fromObject2 = JSONObject.fromObject(new Student(1,"haha","heihei")); //JSONObject转对象 Student student = (Student)JSONObject.toBean(fromObject2,Student.class); System.out.println(student);//Student [id=1, name=haha, sex=heihei] System.out.println(fromObject2);//{"sex":"heihei","name":"haha","id":1} //测试JSONArray,JSONArray里面存的是JSONObject //JSONArray,json数组,使用[],里面是一条条json格式的数据 JSONArray jsonArr = new JSONArray(); JSONObject jsonObj2 = new JSONObject(); jsonObj2.put("1", "一"); jsonObj2.put("2", "二"); jsonObj2.accumulate("3", "三"); jsonArr.add(jsonObj); jsonArr.add(jsonObj2); System.out.println(jsonArr);//[{"1":"一","2":"二","3":"三"},{"1":"一","2":"二","3":"三"}] }
转载请注明原文地址: https://www.6miu.com/read-54301.html

最新回复(0)