Java基础-处理json字符串解析案例
作者:尹正杰
版权声明:原创作品,谢绝转载!否则将追究法律责任。
作为一名开发人员,想必大家或多或少都有接触到XML文件,XML全称为“extensible markup language”,即可扩展性标记语言。它由于可读性很好,但是在网络传输上,这种数据格式往往很占用带宽等诸多缺点,因此就诞生了Json,它比XML数据更小、更快、更容易解析。数据由名称-值 对表示,由逗号分隔开,花括号保存对象,方括号保存数组。Json值可以是:数字/字符串/逻辑值/数组/对象/null。
接下来我们就一起看看如何创建一个json文件以及如何解析json文件。
一.java自定义对象对象和json字符串的互转
1>.添加Maven依赖(添加最后一个依赖json即可)
1 <?xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 5 <modelVersion>4.0.0</modelVersion> 6 7 <groupId>groupId</groupId> 8 <artifactId>MyHadoop</artifactId> 9 <version>1.0-SNAPSHOT</version> 10 11 <dependencies> 12 <dependency> 13 <groupId>org.apache.hadoop</groupId> 14 <artifactId>hadoop-client</artifactId> 15 <version>2.7.3</version> 16 </dependency> 17 18 <!-- https://mvnrepository.com/artifact/junit/junit --> 19 <dependency> 20 <groupId>junit</groupId> 21 <artifactId>junit</artifactId> 22 <version>4.12</version> 23 <scope>test</scope> 24 </dependency> 25 26 <dependency> 27 <groupId>mysql</groupId> 28 <artifactId>mysql-connector-java</artifactId> 29 <version>5.1.17</version> 30 </dependency> 31 <dependency> 32 <groupId>com.alibaba</groupId> 33 <artifactId>fastjson</artifactId> 34 <version>1.2.47</version> 35 </dependency> 36 37 </dependencies> 38 39 </project>
2>.具体实现代码如下:
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie.json; 7 8 public class Teacher { 9 private String name; 10 private int age; 11 12 public Teacher(String name, int age) { 13 this.name = name; 14 this.age = age; 15 } 16 17 public Teacher() { 18 } 19 20 public String getName() { 21 return name; 22 } 23 24 public void setName(String name) { 25 this.name = name; 26 } 27 28 public int getAge() { 29 return age; 30 } 31 32 public void setAge(int age) { 33 this.age = age; 34 } 35 36 public String toString() { 37 return "Teacher{" + "name='" + name + ", age=" + age + '}'; 38 } 39 }
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie.json; 7 8 import com.alibaba.fastjson.JSONObject; 9 10 import java.io.FileInputStream; 11 import java.io.FileOutputStream; 12 import java.io.IOException; 13 14 public class JsonOperation { 15 public static final String filePath = "D:\10.Java\IDE\yhinzhengjieData\MyHadoop\JSON\teacher.txt"; 16 17 public static void main(String[] args) throws Exception { 18 generatingJSON(); 19 System.out.println("=============我是分割线============="); 20 parsingJSON(); 21 } 22 //生成json文本 23 private static void generatingJSON() throws IOException { 24 Teacher yzj = new Teacher("尹正杰", 18); 25 String json = JSONObject.toJSONString(yzj); 26 System.out.println(json); 27 FileOutputStream fos = new FileOutputStream(filePath); 28 byte[] buf = new byte[1024]; 29 fos.write(json.getBytes()); 30 fos.close(); 31 } 32 33 //解析json文本 34 private static void parsingJSON() throws IOException { 35 byte[] buf = new byte[1024]; 36 FileInputStream fis = new FileInputStream(filePath); 37 //由于我的文件较小,为了实验方便我就一次性读取出来了 38 JSONObject json = JSONObject.parseObject( new String(buf,0,fis.read(buf))); 39 System.out.println(json); 40 } 41 } 42 43 44 45 46 /* 47 以上代码执行结果如下: 48 {"age":18,"name":"尹正杰"} 49 =============我是分割线============= 50 {"name":"尹正杰","age":18} 51 */
二.Java数据类型和Json互相转换案例
以下是list和json字符串的互转,当然,map的转换json和其方法类似,我这里就不多举例了:
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie.json; 7 8 public class Teacher { 9 private String name; 10 private int age; 11 12 public Teacher(String name, int age) { 13 this.name = name; 14 this.age = age; 15 } 16 17 public Teacher() { 18 } 19 20 public String getName() { 21 return name; 22 } 23 24 public void setName(String name) { 25 this.name = name; 26 } 27 28 public int getAge() { 29 return age; 30 } 31 32 public void setAge(int age) { 33 this.age = age; 34 } 35 36 public String toString() { 37 return "Teacher{" + "name='" + name + ", age=" + age + '}'; 38 } 39 }
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie.json; 7 8 import com.alibaba.fastjson.JSON; 9 import com.alibaba.fastjson.JSONArray; 10 import com.alibaba.fastjson.JSONObject; 11 12 import java.util.ArrayList; 13 import java.util.List; 14 15 public class JsonOperation { 16 17 18 public static void main(String[] args) throws Exception { 19 listToJSON(); 20 System.out.println("=============我是分割线============="); 21 jsonToList(); 22 } 23 public static void listToJSON(){ 24 Teacher yzj = new Teacher("尹正杰",18); 25 Teacher yzj1 = new Teacher("yinzhengjie",19); 26 Teacher yzj2 = new Teacher("YINZHENGJIE",20); 27 List<Teacher> lists=new ArrayList<Teacher>(); 28 lists.add(yzj); 29 lists.add(yzj1); 30 lists.add(yzj2); 31 String listArray=JSONArray.toJSONString(lists); 32 System.out.println("arrayList:"+listArray); 33 } 34 35 public static void jsonToList(){ 36 String str ="{"names":["尹正杰","yinzhengjie"]}"; 37 JSONObject jo = JSON.parseObject(str); 38 JSONArray jsonArray = jo.getJSONArray("names"); 39 for (Object o : jsonArray) { 40 System.out.println(o.toString()); 41 } 42 } 43 } 44 45 /* 46 以上代码执行结果如下: 47 arrayList:[{"age":18,"name":"尹正杰"},{"age":19,"name":"yinzhengjie"},{"age":20,"name":"YINZHENGJIE"}] 48 =============我是分割线============= 49 尹正杰 50 yinzhengjie 51 */
三.小试牛刀
是不是觉得json处理其实蛮简单的,不是吗?接下来我们来练习以下,解析以下的字符串:需要解析商家评论数据:
{"reviewPics":null,"extInfoList":[{"title":"contentTags","values":["环境优雅","性价比高","干净卫生","停车方便","音响效果好"],"desc":"","defineType":0},{"title":"tagIds","values":["24","300","852","506","173"],"desc":"","defineType":0}],"expenseList":null,"reviewIndexes":[2],"scoreList":null}
1 /* 2 @author :yinzhengjie 3 Blog:http://www.cnblogs.com/yinzhengjie/tag/Java%E5%9F%BA%E7%A1%80/ 4 EMAIL:y1053419035@qq.com 5 */ 6 package cn.org.yinzhengjie.json; 7 8 import com.alibaba.fastjson.JSON; 9 import com.alibaba.fastjson.JSONArray; 10 import com.alibaba.fastjson.JSONObject; 11 12 import java.util.ArrayList; 13 import java.util.List; 14 15 public class JsonOperation { 16 17 18 public static void main(String[] args) throws Exception { 19 String comment = "{"reviewPics":null,"extInfoList":[{"title":"contentTags","values":["环境优雅","性价比高","干净卫生","停车方便","音响效果好"],"desc":"","defineType":0},{"title":"tagIds","values":["24","300","852","506","173"],"desc":"","defineType":0}],"expenseList":null,"reviewIndexes":[2],"scoreList":null}"; 20 List<String> taggen = taggen(comment); 21 for (String s : taggen) { 22 System.out.println(s); 23 } 24 25 } 26 /** 27 * 解析商家评论数据 28 */ 29 public static List<String> taggen(String comment){ 30 JSONObject jo = JSON.parseObject(comment); 31 JSONArray jArray = jo.getJSONArray("extInfoList"); 32 if(jArray != null && jArray.size() != 0){ 33 List<String> list = new ArrayList<String>(); 34 //通过jArray得到第一个json串,作为json对象 35 JSONObject jo2 = jArray.getJSONObject(0); 36 JSONArray jArray2 = jo2.getJSONArray("values"); 37 if(jArray2 != null && jArray2.size() != 0){ 38 for (Object o : jArray2) { 39 //System.out.println(o.toString()); 40 list.add(o.toString()); 41 } 42 return list; 43 } 44 } 45 return null; 46 } 47 } 48 49 /* 50 以上代码执行结果如下: 51 环境优雅 52 性价比高 53 干净卫生 54 停车方便 55 音响效果好 56 */
”