Json、Gson、FAST-JSON解析学习
2016-08-08 21:23
447 查看
Json
JavaScript Object Notation javascript表示对象的一种方式基于JavaScript语言的轻量级的数据交换格式;即:用来传输数据的一种格式.不管是web应用,还是android应用,现在传输数据的方式更多是采用json的格式。我们来对比下json同XML的差别
Android也已经内置了对json解析的支持,所以不需要导入jar包。
需要的jar包:
两个类:
当json字符串以”{“开始,用JSONObject解析
当json字符串以”[“开始,用JSONArray解析
JSONObject
|–getString(String key)根据键找到对应该的值
|–getInt(String key) 得到int类型的值
|–getJSONObject(String key)得到JSONObject
|–put(String key,String/Boolean/Object^^)
构造方法
|–new JSONObject(String source) 把对应的String类型的JSON数据转成JSON的对象
|–new JSONObject(Object bean) 将bean对象转成Json对象,用于转成json字符串
JSONArray |--getJSONObject(int index); |--length() 构造方法 |--new JSONArray(Collection list) |--new JSONArray(String jStr) 特点 {}----遇到{}用JSONObject []----遇到[]用JSONArray 解析用带参构造创建对象 组装用空参构造创建对象
下面用一个Demo来演示下Json解析
车类public class Car { private String brand; //车型 private String color;//车的颜色 private int price; //车的价钱 public Car(String brand, String color, int price) { //有参构造 super(); this.brand = brand; this.color = color; this.price = price; } public Car() {//无参构造 super(); // TODO Auto-generated constructor stub } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } @Override public String toString() { //重写toString return "Car [brand=" + brand + ", color=" + color + ", price=" + price + "]"; } }
车展的类
import java.util.List; public class ShowObj { private String address;//车展的地址 private String time; //车展示的时间 private List<Car> carList; //车展中的众多车的集合 public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public List<Car> getCarList() { return carList; } public void setCarList(List<Car> carList) { this.carList = carList; } @Override public String toString() { return "ShowObj [address=" + address + ", time=" + time + ", carList=" + carList + "]"; } }
import java.util.ArrayList; import java.util.List; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; //new Car("宝马","150","red"); /* * json字符串: * 1.表示对象 * {brand:'宝马',color:'red',price:150} * 2.表示数组 * [{brand:'宝马',color:'red',price:150},{brand:'路虎',color:'black',price:180},{brand:'法拉利',color:'yellow',price:200}] * * 3.表示复杂的对象 * Engine engine = new Engine("华为","400"); * Car car = new Car("宝马", "red", 150, engine ); * * {brand:'宝马',color:'red',price:150,engine:{company:'华为',horsePower:'400'}} * * 4.表示含有数组或者集合的对象:比如说描述车展:车展的地点,车展的时间,车展的参展车型 * {address:'深圳湾体育馆',time:'2016-10-1',cars:[{brand:'宝马',color:'red',price:150},{brand:'路虎',color:'black',price:180},{brand:'法拉利',color:'yellow',price:200}]} * * * 总结: * json对象用{},看见{}就是json对象 * json数组[],看见[]就是json对象组成的数组 ******************************************************** * xml: <car> <brand>宝马</brand> <color>red</color> <price>150</price> </car> *jso和xml的区别:----面试 *json数据量小,可读性差。只用于保存数据 *xml数据量大,可读性好。可以用于软件配置和布局绘制 * ********************************************************* *json解析三种:原生解析(最灵活,步骤繁杂)/fastjson/gson() * *1.原生解析 *步骤: * 导入jar包 * 看见{},创建JSONObject对象 * 看见[],创建JsonArray对象 * * * */ public class Json2ObjDemo { public static void main(String[] args) throws JSONException { testObject(); //对象的json数据解析 testArray(); //数组的Json数据解析 testFuZa(); //复杂Json数据解析 } // 解析对象 private static void testObject() throws JSONException { String jsonStr = "{brand:'宝马',price:150,clr:'red'}"; // 1.解析简单对象:参数是要解析的字符串 JSONObject jObject = new JSONObject(jsonStr); // 2.解析 Car car = new Car(); String brand = jObject.getString("brand"); car.setBrand(brand); car.setColor(jObject.getString("clr")); car.setPrice(jObject.getInt("price")); System.out.println(car); } } // 解析数组 private static void testArray() throws JSONException { String jsonString = "[{brand:'宝马',color:'red',price:150},{brand:'路虎',color:'black',price:180},{brand:'法拉利',color:'yellow',price:200}]"; //这里我们看到以"["开头那么果断new一个JSON的数组 JSONArray jArray = new JSONArray(jsonString); // System.out.println(jArray.length()); List<Car> carList = new ArrayList<>(); for (int i = 0; i < jArray.length(); i++) {//通过遍历获取每个对象 JSONObject jObject = jArray.getJSONObject(i); Car car = new Car(); car.setBrand(jObject.getString("brand")); car.setColor(jObject.getString("color")); car.setPrice(jObject.getInt("price")); carList.add(car);//添加到车集 } System.out.println(carList); } // 解析含有数组或者集合的对象 private static void testFuZa() throws JSONException { /*这个json数据相对复杂 可以看做一个对象中除了自己的普通成员变量外还嵌套了一个Car类型的的集合,从这里的分析我们可以创建好类也就是ShowObj中定义一个Car集的原意*/ String jString = "{address:'深圳湾体育馆',time:'2016-10-1',cars:[{brand:'宝马',color:'red',price:150},{brand:'路虎',color:'black',price:180},{brand:'法拉利',color:'yellow',price:200}]}";//将要解析的JSON字符串 JSONObject jsonObject = new JSONObject(jString); //看见"{"所以我们new一个JSONObject类 ShowObj sObj = new ShowObj(); //创建出车展的对象 //将获取的地址为车站对象初始化 sObj.setAddress(jsonObject.getString("address")); //将获取的车展时间为车站对象初始化 sObj.setTime(jsonObject.getString("time")); // 先获得json数组对象 JSONArray jArray = jsonObject.getJSONArray("cars");//这里通过jsonObject获取一个对象数组接下来就是遍历这个数组中的每个对象然后获取每个对象的值 List<Car> carList = new ArrayList<>();//创建一个Car集 for (int i = 0; i < jArray.length(); i++) { JSONObject jObject = jArray.getJSONObject(i);//获取的一个JSON对象 Car car = new Car();//new一个车 car.setBrand(jObject.getString("brand"));//为这个车赋值 car.setColor(jObject.getString("color"));//为这个车赋值 car.setPrice(jObject.getInt("price"));//为这个车赋值 carList.add(car);//每得到一个车就添加到list中 } sObj.setCarList(carList);//设置车站的车集属性 //至此一个相对复杂的JSON数据就解析完成了我们打印下结果 //这里主要的思想是观察JSON数据的结构创建相应类用于保存数据 System.out.println(sObj); }
读者可能会想这么麻烦竟然JAVA采用面向对象的思想那么有没有更快捷的工具类为我们提供解析呢? 肯定有 == 下面我们来看看更快速的解析
Gson
public class Car { //车类 private String brand; //车型 private String color; //车颜色 private double price; //车价格 private Prduct engine; //车的引擎 public Prduct getEngine() { return engine; } public void setEngine(Prduct engine) { this.engine = engine; } public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public Car(String brand, String color, double price) { super(); this.brand = brand; this.color = color; this.price = price; } @Override public String toString() { return "Car [brand=" + brand + ", color=" + color + ", price=" + price + ", engine=" + engine + "]"; } }
public class Prduct { //车引擎产地 private String company; private String horsePower; public String getCompany() { return company; } public void setCompany(String company) { this.company = company; } public String getHorsePower() { return horsePower; } public void setHorsePower(String horsePower) { this.horsePower = horsePower; } @Override public String toString() { return "Prduct [company=" + company + ", horsePower=" + horsePower + "]"; } }
import java.util.List; public class Show { private String address; //车展的地址 private String time; //车展时间 private List<Car> cars; // 对象名要跟String中一样 public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public List<Car> getCars() { return cars; } public void setCars(List<Car> cars) { this.cars = cars; } @Override public String toString() { return "Show [address=" + address + ", time=" + time + ", cars=" + cars + "]"; } }
import java.util.List; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; public class goson1 { public static void main(String[] args) { // 解析對象json String json = "{brand:'宝马',color:'red',price:150,engine:{company:'华为',horsePower:'400'}}"; Gson gson = new Gson(); Car c = gson.fromJson(json, Car.class); System.out.println(c); // 解析數組json String json2 = "[{brand:'宝马',color:'red',price:150},{brand:'路虎',color:'black',price:180},{brand:'法拉利',color:'yellow',price:200}]"; TypeToken<List<Car>> typeToken = new TypeToken<List<Car>>() { }; List<Car> list = gson.fromJson(json2, typeToken.getType()); System.out.println(list); // 混合型 String json3 ="{address:'深圳湾体育馆',time:'2016-10-1',cars:[{brand:'宝马',color:'red',price:150},{brand:'路虎',color:'black',price:180},{brand:'法拉利',color:'yellow',price:200}]}"; Show show = gson.fromJson(json3, Show.class); System.out.println(show); } }
public static void main(String[] args) { //解析對象json String json = "{brand:'宝马',color:'red',price:150,engine:{company:'华为',horsePower:'400'}}"; Gson gson = new Gson(); Car c = gson.fromJson(json, Car.class); System.out.println(c); //解析數組json String json2 = "[{brand:'宝马',color:'red',price:150},{brand:'路虎',color:'black',price:180},{brand:'法拉利',color:'yellow',price:200}]"; TypeToken<List<Car>> typeToken = new TypeToken<List<Car>>(){}; List<Car> list = gson.fromJson(json2, typeToken.getType()); System.out.println(list); //混合型 String json3 = "{address:'深圳湾体育馆',time:'2016-10-1',cars:[{brand:'宝马',color:'red',price:150},{brand:'路虎',color:'black',price:180},{brand:'法拉利',color:'yellow',price:200}]}"; Show show =gson.fromJson(json3, Show.class); System.out.println(show); }
通过以上代码我们发现Gson的解析异常方便 这里总结下它的用法:
Gson 是 Google 提供的用来在 Java 对象和 JSON 数据之间进行映射的 Java 类库。可以将一个 JSON 字符串转成一个 Java 对象,或者反过来。 需要jar包: > **用法:** Gson gson=new Gson() 1) fromJson(String json,Class<T>.class)把JSON转成对应的对象【注意】:类和属性和json的键要对应 2) fromJson(String json,new TypeToken<List<Person>>() {}.getType())把JSON转成集合 3) toJson(Object obj) 把任何对象转成JSON
使用Gson要注意的一点,这里的list集合的车集合对象名一定要和要解析的json数据对应否则list将获取不到数据比如这里的:
private List<Car> cars ; //对象名要跟String中一样
FAST-JSON
那么讲完JSON GSON解析,下面讲解下阿里云提供的API FASTJSON先看他的方法
Fastjson API入口类是com.alibaba.fastjson.JSON,常用的序列化操作都可以在JSON类上的静态方法直接完成。 // 把JSON文本parse为JavaBean public static final <T> T parseObject(String text, Class<T> clazz); //把JSON文本parse成JavaBean集合 public static final <T> List<T> parseArray(String text, Class<T> clazz); // 将JavaBean序列化为JSON文本 public static final String toJSONString(Object object);
我们发现这里的方法都是静态的所以我们不需要创建fastjson对象直接类名.方法调用 ,当然它的用法跟Gson累死不够效率却高了许多,至于内部实现暂时不研究。。。
具体的用法读者可自行研究一下。今天的分享就到此~
相关文章推荐
- Andorid中使用Gson和Fast-json解析库解析JSON数据---第三方库学习笔记(二)
- JSON解析学习笔记(json、gson、fastjson)
- Java学习总结(二十)——JSON解析:官方解析,GSON解析,FastJSON解析,
- 【幻化万千戏红尘】qianfengDay29-Json解析、Gson解析、FASTJSON解析基础学习:
- Android学习(二):解析JSON,GSON,FASTJSON;JDBC编程
- 学习开源JSON框架 -- FastJson,Jackson,Gson
- Gson与FastJson解析性能分析
- Json,Gson,FastJson解析笔记
- Json,Gson,FastJson解析笔记
- Android学习之Json解析库Gson
- Android中Json数据解析(二)--使用Gson、Jackson和FastJson解析Json数据
- android 学习笔记 解析json格式的数据 JSONObject 和GSON解析json格式数据
- Json,Gson,FastJson解析笔记
- fastjson开发学习(二)---对返回的json进行解析
- Android JSON 解析(Android 原生解析 与 FastJson Gson )性能比较
- gson解析json字符串学习笔记...
- 简单json,FastJson,Gson解析
- Json解析速度比较-Android API、Gson、Fastjson
- FastJson和Gson解析json的小例子
- Gson和Fastjson解析对比