依赖包:json-20180130.jar
MAVEN地址:
1 <dependency> 2 <groupId>org.json</groupId> 3 <artifactId>json</artifactId> 4 <version>20180130</version> 5 </dependency>
比较简单,一看就懂,源码如下:
1 package json; 2 3 import org.json.JSONArray; 4 import org.json.JSONObject; 5 6 import java.util.HashMap; 7 import java.util.Map; 8 9 /** 10 * JSONObject和JSONArray使用:进行JSON对象转换和操作 11 * JSONObject:处理JSON串,多种构造方法,可用于多类型转账。 12 * JSONArray:JSON数组,有顺序 13 */ 14 public class JsonFirst { 15 public static void main(String[] args) { 16 // 1、定义一个json对象 17 JSONObject jo = new JSONObject(); 18 jo.put("id", "1"); 19 jo.put("name", "tom"); 20 jo.put("age", "25"); 21 System.out.println("1、JSONObject: " + jo); 22 // 获取name值 23 String name = jo.getString("name"); 24 System.out.println("查询name:" + name); 25 26 // 2、定义一个Json数组,数组有顺序 27 JSONArray ja = new JSONArray(); 28 ja.put(0, "yang"); 29 ja.put(1, "li"); 30 ja.put(2, "zhang"); 31 ja.put(4, "fouth"); 32 System.out.println("2、JSONArray数组: " + ja); 33 // 获取第四个值 34 String fouth = ja.getString(4); 35 System.out.println("查询第四个:" + fouth); 36 37 // 3、json中添加json对象组成复杂JSON 38 jo.put("Object", ja); 39 System.out.println("3、添加JSON对象后: " + jo); 40 41 // 4、String转换为JSON(复杂JSON处理) 42 String str = "{\"name\":\"tom\",\"Object\":[\"yang\",\"li\",\"zhang\",null,\"fouth\"],\"id\":\"1\",\"age\":\"25\"}"; 43 JSONObject jo2 = new JSONObject(str); 44 System.out.println("4、String转换为JSON:" + jo2); 45 System.out.println("name属性值:" + jo2.getString("name")); 46 System.out.println("Object属性值:" + jo2.get("Object").toString()); 47 // 删除Object属性值 48 jo.remove("Object"); 49 System.out.println("删除Object属性值:" + jo); 50 51 // 5、map和JSON转换 52 Map<String, String> map1 = new HashMap<String, String>(); 53 map1.put("name", "Alexia"); 54 map1.put("sex", "female"); 55 map1.put("age", "23"); 56 JSONObject jo3 = new JSONObject(map1); 57 System.out.println("5.1 map转JSON:" + jo3); 58 Map<String, Object> map2 = new HashMap<String, Object>(); 59 map2 = jo3.toMap(); 60 System.out.println("5.2 JSON转map:" + map2); 61 62 // 6、JSONArray中添加map和JSON对象 63 JSONArray jo4 = new JSONArray(); 64 jo4.put(map1); 65 jo4.put(1, "333"); 66 jo4.put(jo); 67 System.out.println("6、JSONArray中添加map和JSON对象:" + jo4); 68 69 } 70 }
运行结果:
1、JSONObject: {"name":"tom","id":"1","age":"25"}
查询name:tom
2、JSONArray数组: ["yang","li","zhang",null,"fouth"]
查询第四个:fouth
3、添加JSON对象后: {"name":"tom","Object":["yang","li","zhang",null,"fouth"],"id":"1","age":"25"}
4、String转换为JSON:{"name":"tom","Object":["yang","li","zhang",null,"fouth"],"id":"1","age":"25"}
name属性值:tom
Object属性值:["yang","li","zhang",null,"fouth"]
删除Object属性值:{"name":"tom","id":"1","age":"25"}
5.1 map转JSON:{"name":"Alexia","age":"23","sex":"female"}
5.2 JSON转map:{sex=female, name=Alexia, age=23}
6、JSONArray中添加map和JSON对象:[{"name":"Alexia","age":"23","sex":"female"},"333",{"name":"tom","id":"1","age":"25"}]