解析json数据

来源:互联网 发布:淘宝人生全本阅读 编辑:程序博客网 时间:2024/05/29 15:57

JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。

简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。

了解json


一、JSON的解析工具有:

1.json-lib

    (1)缺点在于不仅需导入json-lib-2.3-jdk15.jar,还依赖于很多第三方包: 

            commons-beanutils.jar,

            commons-collections-3.2.jar,

            commons-lang-2.6.jar,

            commons-logging-1.1.1.jar,

            ezmorph-1.0.6.jar;

    (2)其次,对于复杂类型的转换,json-lib对于json转换成bean还有缺陷,比如一个类里面会出现另一个类的list或者map集合,

     json-lib从json到bean的 转换就会出现问题。 json-lib在功能和性能上面都不能满足现在互联网化的需求。


2.开源的Jackson
相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。
Jackson对于复杂类型的json转换bean会出现问题,一些集合Map,List的转换出现问题。Jackson对于复杂类型的bean转换Json,
转换的json格式不是标准的Json格式。

3.Google的Gson
Gson是目前功能最全的Json解析神器Gson的应用主要为toJson与fromJson两个转换函数,不依赖额外的jar。
而在使用这种对象转换之前需先创建好对象的类型以及其成员才能成功的将JSON字符串成功转换成相对应的对象。
类里面只要有get和set方法,Gson完全可以将复杂类型的json到bean或bean到json的转换,是JSON解析的神器
Gson在功能上面无可挑剔,但是性能上面比FastJson有所差距。使用时,导入gson-2.8.2.jar。

4.阿里的FastJson
Fastjson是一个Java语言编写的高性能的JSON处理器,不依赖额外的jar
FastJson在复杂类型的Bean转换Json上会出现一些问题,可能会出现引用的类型,导致Json转换出错,需要制定引用。
FastJson采用独创的算法,将parse的速度提升到极致,超过所有json库。使用时导入fastjson-1.2.38.jar。


二、解析json数据

实体类:

package entity;public class Book {private String id;private String name;public Book() {super();}public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Book(String id, String name) {super();this.id = id;this.name = name;}public String toString() {return "Book [id=" + id + ", name=" + name + "]";}}


package entity;import java.util.Set;public class Student {private String name;private int age;private String sex;private String describe;private Set books;public Student() {super();}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public Set getBooks() {return books;}public void setBooks(Set books) {this.books = books;}public String getDescribe() {return describe;}public void setDescribe(String describe) {this.describe = describe;}public Student(String name, int age, String sex, String describe, Set books) {super();this.name = name;this.age = age;this.sex = sex;this.describe = describe;this.books = books;}public String toString() {return "Student [name=" + name + ", age=" + age + ", sex=" + sex+ ", describe=" + describe + ", books=" + books + "]";}}



1. 使用 json-lib 

(1)非日期类型的解析

package jsonDataType;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.HashSet;import java.util.Iterator;import java.util.Map;import java.util.Set;import entity.Book;import entity.Student;import net.sf.json.JSONObject;import net.sf.json.processors.JsonValueProcessor;import net.sf.json.JsonConfig;public class JsonlibTest {public static void main(String[] args) {Book b1 = new Book("001", "红楼梦");Book b2 = new Book("002", "西游记");Book b3 = new Book("003", "三国演义");Set set = new HashSet();set.add(b1);set.add(b2);set.add(b3);Student s = new Student("赵凯鹏", 18, "男", "求职中", set);/* 1.bean转换json */// a)普通的对象转为json串// Object json = JSONObject.fromObject(s) ;// System.out.println(json);// b)将List,Map转换成Json串// Object json = JSONArray.fromObject(set);// System.out.println(json);//// Map<String, Integer> map = new HashMap<String, Integer>();// map.put("name", 123);// map.put("id", 666);// json = JSONArray.fromObject(map);// System.out.println(json);/* 2.json转换bean */// a)普通对象// String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";// JSONObject jsonObj = JSONObject.fromObject(json);// Book book = (Book)JSONObject.toBean(jsonObj,Book.class);// System.out.println(book);// b1)json串转换List,对于复杂类型的转换会出现问题// String json =// "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"Java技术\"}]";// JSONArray jsonArray = JSONArray.fromObject(json);// int size = jsonArray.size();// System.out.println(jsonArray);//// List list = new ArrayList(size);// for (int i = 0; i < size; i++) {// JSONObject jsonObject = jsonArray.getJSONObject(i);// Object bean = JSONObject.toBean(jsonObject, Book.class);// list.add(bean);// }// System.out.println(list);// b2)json转换Map//String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";//JSONObject jsonObject = JSONObject.fromObject(json);//Iterator keyIter = jsonObject.keys();////Map map = new HashMap();//while (keyIter.hasNext()) {//String key = (String) keyIter.next();//Object value = jsonObject.get(key).toString();//map.put(key, value);//}//System.out.println(map);/*3.JsonObject 对于json的操作和处理*/// a)从json串中获取属性// String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}";// Object key = "name";// Object value = null;// JSONObject jsonObject = JSONObject.fromObject(jsonString);// // value = jsonObject.get(key);// System.out.println(value); // b)除去json中的某个属性// String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}";// Object key = "name";// Object value = null;// JSONObject jsonObject = JSONObject.fromObject(jsonString);// // jsonObject.remove(key);// System.out.println(jsonObject); // c)向json中添加和修改属性,有则修改,无则添加// String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}";// Object key = "desc";// Object value = "json的好东西";// JSONObject jsonObject = JSONObject.fromObject(jsonString);// // jsonObject.put(key,value);// System.out.println(jsonObject); // d)判断json中是否有属性// String jsonString = "{\"id\":\"1\",\"name\":\"Json技术\"}";// boolean containFlag = false;// Object key = "desc";// JSONObject jsonObject = JSONObject.fromObject(jsonString);// // containFlag = jsonObject.containsKey(key);// System.out.println(containFlag);/*4.json对于日期的操作比较复杂,需要使用JsonConfig, 比Gson和FastJson要麻烦多了, 见jsonlib_date包*/ }}

(2) 日期的解析

package jsonlib_date;import java.text.DateFormat;import java.text.SimpleDateFormat;import java.util.Date;import net.sf.json.JsonConfig;import net.sf.json.processors.JsonValueProcessor;/* JsonValueProcessor接口: 每个属性的自定义序列化的基本接口。 */  public class DateJsonLib implements JsonValueProcessor {             public static final String Default_DATE_PATTERN = "yyyy-MM-dd";       private DateFormat dateFormat;              public DateJsonLib(String datePattern) {            try {                dateFormat = new SimpleDateFormat(datePattern);            } catch (Exception e) {                dateFormat = new SimpleDateFormat(Default_DATE_PATTERN);            }        }               //processArrayValue:处理值并返回一个合适的JSON值。      public Object processArrayValue(Object value, JsonConfig jsonConfig) {           return process(value);      }          //processObjectValue:处理值并返回一个合适的JSON值。      public Object processObjectValue(String key, Object value, JsonConfig jsonConfig) {          return process(value);      }            private Object process(Object value) {           return dateFormat.format((Date) value); //format 将日期格式化为日期/时间字符串。     }    }

package jsonlib_date;import java.util.Date;import java.util.HashMap;import java.util.Map;import net.sf.json.JSONObject;import net.sf.json.JsonConfig;public class testDate {public static void main(String[] args) {       Map<String, Object> map = new HashMap<String, Object>();         map.put("time", new Date());         map.put("name", "赵凯鹏");         map.put("age", 22);         //System.out.println(map);              /* JsonConfig提供了在对一个Json串和Java对象进行互转时,有选择性的过滤掉一些属性值的方法  */        JsonConfig config = new JsonConfig();         //     注册一个JsonValueProcessor[Java--->JSON] //     public void registerJsonValueProcessor(java.lang.Class propertyType, JsonValueProcessor jsonValueProcessor) //     propertyType-要用作键的属性类型 //     jsonValueProcessor-进行注册是处理器         config.registerJsonValueProcessor(Date.class, new DateJsonLib("yyyy-MM-dd hh:mm:ss.SS"));         //     G 纪年术语 //     yyyy-MM-dd hh:mm:ss.SS 很简单不用解释 //     zzz 一般时区 //     ZZZ RFC 822时区 //     w 年中的周数 //     DDD 年中的天数 //     FF 月份中的星期 //     EE 星期中的天数        JSONObject Obj = JSONObject.fromObject(map, config);         System.out.println(Obj);  }}

2. 使用gson

package jsonDataType;import java.util.Date;import java.util.HashSet;import java.util.List;import java.util.Set;import com.google.gson.Gson;import com.google.gson.GsonBuilder;import com.google.gson.JsonElement;import com.google.gson.JsonObject;import com.google.gson.JsonParser;import com.google.gson.reflect.TypeToken;import entity.Book;import entity.Student;public class gsonTest {public static void main(String[] args) {Gson gson = new Gson();//Book b1 = new Book("001","红楼梦");//Book b2 = new Book("002","西游记");//Book b3 = new Book("003","三国演义");////Set set = new HashSet();//set.add(b1);//set.add(b2);//set.add(b3);////Student s = new Student("赵凯鹏",18,"男","求职中",set);/*1.简单对象的转换*///序列化  object --> String//String str = gson.toJson(s);//System.out.println(str);//反序列化  String --> object//Student stu = (Student) gson.fromJson(str, Student.class);//System.out.println(stu);////String ss = "{\"id\":\"006\",\"name\":\"水浒传\"}";//System.out.println(gson.fromJson(ss, Book.class));        /*2.String转换为复杂的bean,比如List,Set*///String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]";  //将json转换成List  //List lst = (List) gson.fromJson(json,new TypeToken<List>() {}.getType());  //System.out.println(lst);//System.out.println("-------------");//将json转换成Set  //Set st = (Set) gson.fromJson(json,new TypeToken<Set>() {}.getType());//System.out.println(st);/*3.通过json对象直接操作json以及一些json的工具*///a)格式化json字符串//String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]";  //gson = new GsonBuilder().setPrettyPrinting().create();  //JsonParser jp = new JsonParser();  //JsonElement je = jp.parse(json);  //json = gson.toJson(je);  //System.out.println(json);//b1)判断字符串是否是json对象字符串, 通过捕捉的异常来判断是否是json//String string = "{\"id\":\"006\",\"name\":\"水浒传\"}";//try {  //new JsonParser().parse(string).getAsJsonObject();  //} catch (Exception e) {  //System.out.println(e.getMessage());//}  //b2)同理, 判断字符串是否是json数组字符串//try {  //new JsonParser().parse(json).getAsJsonArray();  //} catch (Exception e) {  //System.out.println(e.getMessage());//} //c)从json串中获取属性//String s1 = "{\"id\":\"1\",\"name\":\"Json技术\"}";  //String propertyName = "id";  //int propertyValue;  //try {  //JsonParser jp = new JsonParser();  //JsonElement element = jp.parse(s1);  //JsonObject jsonObj = element.getAsJsonObject(); ////propertyValue = jsonObj.get(propertyName).getAsInt();  //System.out.println(propertyValue);//} catch (Exception e) {  //System.out.println(e.getMessage());  //}//d)除去json中的某个属性//String js1 = "{\"id\":\"1\",\"name\":\"Json技术\"}";  //String propertyName = "id"; //JsonParser jsonParser = new JsonParser();  //JsonElement element = jsonParser.parse(js1);  //JsonObject jsonObj = element.getAsJsonObject();  ////jsonObj.remove(propertyName);  //String json = jsonObj.toString(); //System.out.println(json);//e)向json中添加属性//String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";  //String propertyName = "desc";  //int propertyValue = 123;  //JsonParser jsonParser = new JsonParser();  //JsonElement element = jsonParser.parse(json);  //JsonObject jsonObj = element.getAsJsonObject();  ////jsonObj.addProperty(propertyName, propertyValue);  //json = jsonObj.toString(); //System.out.println(json);//f)修改json中的属性//String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";  //String propertyName = "name";  //String propertyValue = "c++";  //JsonParser jsonParser = new JsonParser();  //JsonElement element = jsonParser.parse(json);  //JsonObject jsonObj = element.getAsJsonObject();  ////jsonObj.remove(propertyName);  //jsonObj.addProperty(propertyName, propertyValue);  //json = jsonObj.toString();  //System.out.println(json);//g)判断json中是否有属性//String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";  //String propertyName = "name";  //boolean isContains = false ;  //JsonParser jsonParser = new JsonParser();  //JsonElement element = jsonParser.parse(json);  //JsonObject jsonObj = element.getAsJsonObject();  ////isContains = jsonObj.has(propertyName); //System.out.println(isContains);//h)json中日期格式的处理//GsonBuilder builder = new GsonBuilder();  //builder.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS");  //gson = builder.create();  ////String date = gson.toJson(new Date());//System.out.println(date);//i)json中对于Html的转义  GsonBuilder builder = new GsonBuilder();  builder.disableHtmlEscaping();  gson = builder.create();  //这种对象默认对Html进行转义,如果不想转义使用下面的方法 }}

3. 使用fastjson

package jsonDataType;import java.util.ArrayList;import java.util.Date;import java.util.HashSet;import java.util.List;import java.util.Set;import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.TypeReference;import entity.Book;import entity.Student;public class fastJsonTest {public static void main(String[] args) {Book b1 = new Book("001","红楼梦");Book b2 = new Book("002","西游记");Book b3 = new Book("003","三国演义");Set set = new HashSet();set.add(b1);set.add(b2);set.add(b3);Student s = new Student("赵凯鹏",18,"男","求职中",set);/*1.简单对象的转换*///将对象转换成格式化的json  //String s1 = JSON.toJSONString(s,true);  //System.out.println(s1);//将对象转换成非格式化的json  //String s2 = JSON.toJSONString(s,false);  //System.out.println(s2);//将json转换成格式化的对象//String json = "{\"id\":\"2\",\"name\":\"Json技术\"}";  //Book book = JSON.parseObject(json, Book.class); //System.out.println(book);/*2.json转换复杂的bean,比如List,Map*///String json = "[{\"id\":\"1\",\"name\":\"Json技术\"},{\"id\":\"2\",\"name\":\"java技术\"}]";  //将json转换成List  //List list = JSON.parseObject(json,new TypeReference<List>(){});  //System.out.println(list);//将json转换成Set  //set = JSON.parseObject(json,new TypeReference<Set>(){});  //System.out.println(set);/*3.通过json对象直接操作json*///a)从json串中获取属性//String propertyName = "id";  //String propertyValue = "";  //String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";  //JSONObject obj = JSON.parseObject(json);  ////propertyValue = (String) obj.get(propertyName); //System.out.println(propertyValue);//b)除去json中的某个属性//String propertyName = "id";//String propertyValue = "";  //String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";  //JSONObject obj = JSON.parseObject(json);  ////obj.remove(propertyName); //等价于下面两句////set = obj.keySet();  //set.remove(propertyName); ////json = obj.toString();  //System.out.println(json);//c)向json中添加属性//String propertyName = "desc";  //Object propertyValue = "json的玩意儿";  //String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";  //JSONObject obj = JSON.parseObject(json);////obj.put(propertyName, propertyValue);  //json = obj.toString();//System.out.println(json);//d)修改json中的属性//String propertyName = "name";  //int propertyValue = 666;  //String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";  //JSONObject obj = JSON.parseObject(json);  ////set = obj.keySet();  //if(set.contains(propertyName)){//obj.put(propertyName, propertyValue); //} //json = obj.toString();  //System.out.println(json);//e)判断json中是否有属性//String propertyName = "name";  //boolean isContain = false;  //String json = "{\"id\":\"1\",\"name\":\"Json技术\"}";  //JSONObject obj = JSON.parseObject(json);  ////set = obj.keySet();  //isContain = set.contains(propertyName);  //System.out.println(isContain);//f)json中日期格式的处理  String json = JSON.toJSONStringWithDateFormat(new Date(), "yyyy-MM-dd HH:mm:ss.SSS");  System.out.println(json);}}



三、解析json文件(仅以fastjson为例)

E:/MyEclipse/json/book.json:

{    "user":{        "name":"赵凯鹏",        "age":23,        "birth":"1991-10-28 00:00:00",        "address":"北京"    },    "array":[        10,        20,        30    ],    "arraylist":[        {            "name0":"赵0",            "age0":10,            "addr0":"科技0路"        },        {            "name1":"赵1",            "age1":11,            "addr1":"科技1路"        },        {            "name2":"赵2",            "age2":12,            "addr2":"科技2路"        }    ]}


1. 读取json文件数据

package fastjsonFileType;import java.io.FileNotFoundException;import java.io.FileReader;import com.alibaba.fastjson.JSONReader;public class FastJsonReaderFile {public static void main(String[] args) {JSONReader reader = null;try {reader = new JSONReader(new FileReader("E:/MyEclipse/json/book.json"));} catch (FileNotFoundException e) {e.printStackTrace();}reader.startObject();while(reader.hasNext()){String name = reader.readString();String value = reader.readObject().toString();System.out.println(name+":"+value);}reader.endObject();reader.close();}}

控制台:

user:{"address":"北京","name":"赵凯鹏","birth":"1991-10-28 00:00:00","age":23}array:[10,20,30]arraylist:[{"addr0":"科技0路","age0":10,"name0":"赵0"},{"addr1":"科技1路","name1":"赵1","age1":11},{"addr2":"科技2路","name2":"赵2","age2":12}]

2. 先写入json文件,然后读取json文件

package fastjsonFileType;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.sql.Date;import com.alibaba.fastjson.JSONReader;import com.alibaba.fastjson.JSONWriter;import com.alibaba.fastjson.serializer.SerializerFeature;public class FastJsonReaderWriter {public static void main(String[] args) {/*fastjson写入文件:voidconfig(SerializerFeature feature, boolean state)  voidstartArray()    voidendArray()  voidstartObject() voidendObject()//写key (对于json而言, key一定是字符串)voidwriteKey(String key)  //写valuevoidwriteKey(String key)voidwriteObject(Object object) voidwriteObject(String object) voidwriteValue(Object object)voidflush()voidclose() */ //JSONWriter writer = null;//try {//writer = new JSONWriter(new FileWriter("E:/MyEclipse/json/book.json"));//} catch (IOException e) {//e.printStackTrace();//}////writer.config( SerializerFeature.WriteDateUseDateFormat, true);////writer.startObject(); // start { ////writer.writeKey("user");//writer.startObject();//writer.writeKey("name");//writer.writeObject("赵凯鹏");  //writer.writeKey("age");//writer.writeObject(23);//writer.writeKey("birth");//writer.writeObject(Date.valueOf("1991-10-28"));//writer.writeKey("address");//writer.writeObject("北京");//writer.endObject();////writer.writeKey("array");//writer.startArray();//writer.writeObject(10);//writer.writeObject(20);//writer.writeObject(30);//writer.endArray();////writer.writeKey("arraylist");//writer.startArray();//for(int i=0; i<3; i++){//writer.startObject();//writer.writeKey("name"+i);//writer.writeObject("赵"+i);//writer.writeKey("age"+i);//writer.writeObject(i+10);//writer.writeKey("addr"+i);//writer.writeObject("科技"+i+"路");//writer.endObject();//}//writer.endArray();////writer.endObject(); // end }////try {//writer.flush();//writer.close();//} catch (IOException e) {//e.printStackTrace();//}////System.out.println("writer success");//-----------------------------------------------------------------------------/*fastjson读出文件:voidconfig(Feature feature, boolean state) voidstartArray() voidstartObject()voidendArray() voidendObject() LocalegetLocal() TimeZonegetTimzeZone() booleanhasNext() //读key (key一定是字符串)StringreadString()//读valueStringreadString()IntegerreadInteger() LongreadLong() ObjectreadObject() <T> TreadObject(Class<T> type) ObjectreadObject(Map object) voidreadObject(Object object) <T> TreadObject(Type type) <T> TreadObject(TypeReference<T> typeRef)  voidsetLocale(Locale locale) voidsetTimzeZone(TimeZone timezone) voidclose() */ JSONReader reader =null;//读取方式一 (剥洋葱, 一层一层剥)try {reader = new JSONReader(new FileReader("E:/MyEclipse/json/book.json"));} catch (FileNotFoundException e) {e.printStackTrace();}reader.startObject();while(reader.hasNext()){ String key = reader.readString(); if(key.equals("user")){ System.out.println(key); reader.startObject(); while(reader.hasNext()){key = reader.readString();String value = reader.readObject().toString();System.out.println(key+":"+value); } reader.endObject(); System.out.println("--------------"); }  if(key.equals("array")){ System.out.println(key); reader.startArray(); while(reader.hasNext()){String value = reader.readObject().toString();System.out.println(value); } reader.endArray(); System.out.println("--------------"); }  if(key.equals("arraylist")){ System.out.println(key); reader.startArray(); while(reader.hasNext()){reader.startObject(); while(reader.hasNext()){key = reader.readString();String value = reader.readObject().toString();System.out.println(key+":"+value);}reader.endObject();System.out.println("------"); } reader.endArray(); } }}}

写入后的数据:即 E:/MyEclipse/json/book.json 中的数据;

读取的数据如下控制台:

username:赵凯鹏age:23birth:1991-10-28 00:00:00address:北京--------------array102030--------------arraylistname0:赵0age0:10addr0:科技0路------name1:赵1age1:11addr1:科技1路------name2:赵2age2:12addr2:科技2路------



3. 对象数组写入json文件,然后读出数据

package fastjsonFileType;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.sql.Date;import com.alibaba.fastjson.JSONReader;import com.alibaba.fastjson.JSONWriter;import com.alibaba.fastjson.serializer.SerializerFeature;public class FastJsonReaderWriterArrayList {public static void main(String[] args) {//JSONWriter writer = null;//try {//writer = new JSONWriter(new FileWriter("E:/MyEclipse/json/book2.json"));//} catch (IOException e) {//e.printStackTrace();//}////writer.config( SerializerFeature.WriteDateUseDateFormat, true);////writer.startObject(); // start { ////writer.writeKey("arraylist");//writer.startArray();//for(int i=0; i<3; i++){//writer.startObject();//writer.writeKey("name"+i);//writer.writeObject("赵"+i);//writer.writeKey("age"+i);//writer.writeObject(i+10);//writer.writeKey("addr"+i);//writer.writeObject("科技"+i+"路");//writer.endObject();//}//writer.endArray();////writer.endObject(); // end }////try {//writer.flush();//writer.close();//} catch (IOException e) {//e.printStackTrace();//}//System.out.println("writer success");//-----------------------------------------------------------------------------JSONReader reader =null;try {reader = new JSONReader(new FileReader("E:/MyEclipse/json/book2.json"));} catch (FileNotFoundException e) {e.printStackTrace();}reader.startObject();if(reader.hasNext()){String key = reader.readString();System.out.println(key);reader.startArray();while(reader.hasNext()){String a = reader.readObject().toString();System.out.println(a);} reader.endArray();}reader.endObject();reader.close();}}

E:/MyEclipse/json/book2.json :

{    "arraylist":[        {            "name0":"赵0",            "age0":10,            "addr0":"科技0路"        },        {            "name1":"赵1",            "age1":11,            "addr1":"科技1路"        },        {            "name2":"赵2",            "age2":12,            "addr2":"科技2路"        }    ]}


控制台:

arraylist{"addr0":"科技0路","age0":10,"name0":"赵0"}{"addr1":"科技1路","name1":"赵1","age1":11}{"addr2":"科技2路","name2":"赵2","age2":12}



4. 基本类型数组写入json文件,然后读取文件

package fastjsonFileType;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.sql.Date;import com.alibaba.fastjson.JSONReader;import com.alibaba.fastjson.JSONWriter;import com.alibaba.fastjson.serializer.SerializerFeature;public class FastJsonReaderWriterArray {public static void main(String[] args) {//JSONWriter writer = null;//try {//writer = new JSONWriter(new FileWriter("E:/MyEclipse/json/book3.json"));//} catch (IOException e) {//e.printStackTrace();//}////writer.config( SerializerFeature.WriteDateUseDateFormat, true);////writer.startObject(); // start { ////writer.writeKey("array");//writer.startArray();//writer.writeObject(10);//writer.writeObject(20);//writer.writeObject(30);//writer.endArray();////writer.endObject(); // end }////try {//writer.flush();//writer.close();//} catch (IOException e) {//e.printStackTrace();//}////System.out.println("writer success");//-----------------------------------------------------------------------------JSONReader reader =null;try {reader = new JSONReader(new FileReader("E:/MyEclipse/json/book3.json"));} catch (FileNotFoundException e) {e.printStackTrace();}reader.startObject();if(reader.hasNext()){String key = reader.readString();System.out.println(key);reader.startArray();while(reader.hasNext()){String a = reader.readObject().toString();System.out.println(a);} reader.endArray();}reader.endObject();reader.close();}}


E:/MyEclipse/json/book3.json:

{"array":[10,20,30]}


控制台:

array102030

参考:zzz && kkk 


原创粉丝点击