java中json的使用和解析
1.创建json对象
1.1 创建JSONObject对象
使用map初始化json
@Test public void test1() { Map<String, Object> map = new LinkedHashMap<String, Object>(); map.put("name", "孙笑川"); map.put("age", 25); map.put("height", 1.70); map.put("major", new String[] { "理发", "挖掘机" }); map.put("hasGirlFriend", false); map.put("car", null); map.put("house", null); //null作为value时,转换成json后不会保存 JSONObject json1 = new JSONObject(map); System.out.println(json1.toString()); Map map2 = json1.toMap(); System.out.println(map2.toString()); }
可以看到,当value为null时,转化为json后不会保存,会直接抛弃。
使用javabean初始化json
//javaBean class Person { public String name; public int age; public String idCard; //省略getter&setter } //使用javaBean初始化json @Test public void test2() { Person person = new Person(); person.setName("孙亚龙"); person.setAge(30); person.setIdCard("512445546565164641212"); JSONObject json2 = new JSONObject(person); System.out.println(json2.toString()); }
直接创建JSONObject
@Test public void test3() { JSONObject json3 = new JSONObject(); Object nullObj = null; json3.put("name", "孙悟空"); json3.put("changeTimes", 72); json3.put("name", "MonkeySun"); //put方法:value保留原格式,若key相等,value会覆盖原值 json3.put("isHuman", false); json3.append("nickName", "齐天大圣"); //append方法:value存放在数组中,若key相等,value会覆盖原值 json3.append("nickName", "弼马温"); json3.accumulate("Teacher", "元始天尊"); //accmulate方法,和append方法一样 json3.accumulate("Teacher", "唐三藏"); System.out.println(json3.toString()); }
1.2 创建JSONArray对象
直接从字符串获取:
用给定的字符串初始化JSONArray对象,字符串最外层必须为中括号包裹:
@Test public void test12() { String jsonString = "[\'white\',\'卢本伟\',\'芦苇\',\'卢姥爷\']"; JSONArray jsonArray = new JSONArray(jsonString); for (Object object : jsonArray) { System.out.println(object); } }
直接创建JSONArray对象:
创建一个空的JSONArray对象,使用put传值
@Test public void test_1() { JSONArray jsonArray = new JSONArray(); //1.put(value)方法 jsonArray.put("孙悟空"); //2.put(index value)方法 jsonArray.put(1,"{\'变化\':72,\'武器\',金箍棒}"); System.out.println(jsonArray); }
2.解析json
2.1 官方json包解析
使用官方json包解析时,需要下载json官方jar包,并导入
下载地址(maven仓库):https://mvnrepository.com/artifact/org.json/json/20180813
导入jar包:
import org.json.JSONArray; import org.json.JSONObject;
-
待解析的字符串是简单对象类型,被大括号 { }包围时:
@Test public void test6() { //待解析的json字符串 String jsonString = "{\'name\':\'卢本伟\',\'age\':24,\'Position\':\'Mid\'}"; //因为json字符串是大括号包围,所以用JSONObject解析 JSONObject json = new JSONObject(jsonString); String name = json.getString("name"); int age = json.getInt("age"); String position = json.getString("Position"); System.out.println("姓名:"+name); System.out.println("年龄:"+age); System.out.println("位置"+position); }
- 待解析的字符串是数组类型,被中括号 [ ] 包围时:
@Test public void test7() { //待解析的json字符串 String jsonString = "[\'卢本伟\',\'white\',\'卢伟\',\'五五开\']"; //因为json字符串是大括号包围,所以用JSONArray解析 JSONArray jsonArray = new JSONArray(jsonString); //遍历即可,foreach或for循环 for (Object name : jsonArray) { System.out.println(name); } }
- 待解析的字符串既有中括号 [ ]、又有大括号[ ] 包围时,逐层解析
@Test public void test5() { //待解析的json字符串 String jsonString = "{\'name\':\'卢本伟\',\'age\':24,\'Hero\':{\'name\':\'Fizz\',\'Position\':\'Mid\',\'charactor\':\'killer\'},\'nickNames\':[\'五五开\',\'芦苇\',\'white\'],\'Honors\':[{\'year\':2011,\'name\':\'TGA总决赛冠军\'},{\'year\':2013,\'name\':\'S3全球总决赛中国区冠军\'},{\'year\':2013,\'name\':\'S3全球总决赛亚军\'}]}"; try { //因为json字符串是大括号包围,所以用JSONObject解析 JSONObject json = new JSONObject(jsonString); /* * 普通元素,根据类型直接获取 */ String name = json.getString("name"); int age = json.getInt("age"); System.out.println("姓名:"+name); System.out.println("年龄:"+age); System.out.println("————————————————————————————————"); /* * 属性大括号包括,先获取JSONObject对象 */ JSONObject hero = json.getJSONObject("Hero"); String hero_name = hero.getString("name"); String hero_position = hero.getString("Position"); String hero_charactor = hero.getString("charactor"); System.out.println("擅长英雄:"); System.out.println("英雄名:"+hero_name); System.out.println("位置:"+hero_position); System.out.println("英雄定位:"+hero_charactor); System.out.println("————————————————————————————————"); /* * 属性被中括号包括,获取JSONArray对象,遍历即可 */ System.out.println("外号:"); JSONArray nickNames = json.getJSONArray("nickNames"); for (Object nickName : nickNames) { System.out.println(nickName); } System.out.println("————————————————————————————————"); /* * 属性中既有中括号包括,又嵌套了大括号,一层层获取即可 */ JSONArray Honors = json.getJSONArray("Honors"); System.out.println("所获荣誉:"); for(int i=0;i<Honors.length();i++) { JSONObject honor = Honors.getJSONObject(i); int honor_year = honor.getInt("year"); String honor_name = honor.getString("name"); System.out.println(honor_year+" : "+ honor_name); } }catch(Exception e) { System.out.println(e.getMessage()); } }
2.2 fastjson解析
fastjson是阿里巴巴开源产品之一,解析速度快。
下载地址(maven仓库):https://mvnrepository.com/artifact/com.alibaba/fastjson/1.2.53
- JSON字符串是简单对象类型,被大括号包围:
当待解析的JSON字符串是简单对象类型的,即用大括号包围,此时采用JSONObject对象来处理:
@Test public void test3() { //简单对象类型 String jsonStr = "{\'name\':\'Misaya\',\'position\':\'Mid\',\'hero\':\':Twisted Fate\'}"; JSONObject json = JSON.parseObject(jsonStr); String name = json.getString("name"); System.out.println(name); System.out.println(json); }
- JSON字符串是数组类型,被中括号包围
当待解析的JSON字符串是简单数组类型的,即用中括号包围,此时采用JSONArray对象来处理:
@Test public void test4() { //数组类型 String jsonStr = "[\'元旦\',\'五一\',\'国庆\',\'春节\']"; JSONArray json = JSON.parseArray(jsonStr); String first = (String) json.get(0); System.out.println(first); System.out.println(json); }
- JSON字符串为混合类型,既有简单对象,又有数组,逐层解析
@Test public void test5() { //混合类型 String jsonStr = "[{\'name\':\'元旦\',\'vacation\':\'3\'},{\'name\':\'五一\',\'vacation\':\'7\'},{\'name\':\'国庆\',\'vacation\':\'7\'}]"; JSONArray jsonArr = JSON.parseArray(jsonStr); JSONObject jsonObj1 = jsonArr.getJSONObject(0); System.out.println(jsonObj1); }
- JSON字符串有对应的类时,对象的解析:
1 /** 2 * @Author {LearnAndGet} 3 * @Time 2018年11月24日 4 * @Discription: 5 */ 6 import java.util.Arrays; 7 import java.util.HashMap; 8 9 public class Player { 10 private String name; 11 private int age; 12 private HashMap Hero = new HashMap<String,String>(); 13 private String[] nickNames; 14 private Honor[] Honors; 15 16 public String getName() { 17 return name; 18 } 19 20 public void setName(String name) { 21 this.name = name; 22 } 23 24 public int getAge() { 25 return age; 26 } 27 28 public void setAge(int age) { 29 this.age = age; 30 } 31 32 public HashMap getHero() { 33 return Hero; 34 } 35 36 public void setHero(HashMap hero) { 37 Hero = hero; 38 } 39 40 public String[] getNickNames() { 41 return nickNames; 42 } 43 44 public void setNickNames(String[] nickNames) { 45 this.nickNames = nickNames; 46 } 47 48 public Honor[] getHonors() { 49 return Honors; 50 } 51 52 public void setHonors(Honor[] honors) { 53 Honors = honors; 54 } 55 56 57 @Override 58 public String toString() { 59 return "Player [name=" + name + ", age=" + age + ", Hero=" + Hero + ", nickNames=" + Arrays.toString(nickNames) 60 + ", Honors=" + Arrays.toString(Honors) + "]"; 61 } 62 63 64 static class Honor 65 { 66 int year; 67 String name; 68 public int getYear() { 69 return year; 70 } 71 public void setYear(int year) { 72 this.year = year; 73 } 74 public String getName() { 75 return name; 76 } 77 public void setName(String name) { 78 this.name = name; 79 } 80 @Override 81 public String toString() { 82 return "Honor [year=" + year + ", name=" + name + "]"; 83 } 84 } 85 86 87 }
View Code
@Test public void Json2Obj() { //待解析的json字符串 String jsonString = "{\'name\':\'卢本伟\',\'age\':24,\'Hero\':{\'name\':\'Fizz\',\'Position\':\'Mid\',\'charactor\':\'killer\'},\'nickNames\':[\'五五开\',\'芦苇\',\'white\'],\'Honors\':[{\'year\':2011,\'name\':\'TGA总决赛冠军\'},{\'year\':2013,\'name\':\'S3全球总决赛中国区冠军\'},{\'year\':2013,\'name\':\'S3全球总决赛亚军\'}]}"; Player p = JSON.parseObject(jsonString, Player.class); System.out.println(p); }
2.3 jackson解析
-
解析普通属性
@Test public void getCustomProp() { String jsonStr = "{\"price\":5000,\"count\":100,\"function\":[{\"name\":\"camera\",\"config\":1500},{\"name\":\"music\",\"config\":2000}]}"; try { ObjectMapper objMap = new ObjectMapper(); JsonNode root = objMap.readTree(jsonStr); //在根节点上的属性 int price = root.path("price").asInt(); int count = root.path("count").asInt(); System.out.println("price"+":"+price); System.out.println("count"+":"+count); //在叶子节点上的属性 JsonNode node = root.path("function"); String fun1_name = node.path(0).path("name").asText(); int fun1_config = node.path(0).path("config").asInt(); System.out.println("function1:"+fun1_name+":"+fun1_config); String fun2_name = node.path(1).path("name").asText(); int fun2_config = node.path(1).path("config").asInt(); System.out.println("function2:"+fun2_name+":"+fun2_config); }catch(Exception ex) { System.out.println(ex.getMessage()); } }
-
解析对象字符串
//省略javaBean:Person的代码
@Test public void json2obj() { String jsonStr = "{\"name\":\"二狗\",\"age\":15,\"idCard\":\"42125\"}"; try { ObjectMapper objMapper = new ObjectMapper();
//当反序列化json时,未知属性会引起的反序列化被打断,这里我们禁用未知属性打断反序列化功能 objMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); Person p = objMapper.readValue(jsonStr, Person.class); System.out.println(p); }catch(Exception e) { System.out.println(e.getMessage()); } } -
解析对象数组构成的字符串
//省略 javaBean:Person代码
/* * 解析对象数组构成的String */ @Test public void jackSonTest() { String jsonStr = "[{\"name\":\"二狗\",\"age\":15,\"idCard\":\"42125\"},{\"name\":\"铁柱\",\"age\":12,\"idCard\":\"46521\"}]"; try { ObjectMapper mapper = new ObjectMapper(); TreeNode treeNode = mapper.readTree(jsonStr); List<Person> persons = mapper.readValue(jsonStr, new TypeReference<List<Person>>(){}); for (Person person : persons) { System.out.println(person); } }catch(Exception e) { System.out.println(e.getMessage()); } }