經過Json和Gson,快速生成和解析json字符串

1,首先咱們要先明白json與gson有什麼區別java

其實他們是徹底不一樣的概念:json

json是一種數據格式,便於數據傳輸,存儲,交換。dom

gson則是一種組件庫,就是經過Gson咱們能夠把java中的對象(gson.toJson()),轉換成Json字符串,固然反過來也是能夠的(gson.fromJson);this

 

2,代碼google

首先咱們須要JSon和Gson這兩個jar包spa

 

package com.json.dome;對象

import java.util.ArrayList;
import java.util.List;字符串

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;get

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;class

public class JsonDome {

public static void main(String[] args) {
// TODO 自動生成的方法存根
//生成json
List<Student> arrayList=new ArrayList<Student>();
Student stu1=new Student("張三", "男");
Student stu2=new Student("李四", "男");
Student stu3=new Student("王二", "女");
arrayList.add(stu1);
arrayList.add(stu2);
arrayList.add(stu3);
Gson gson=new Gson();

//gson.toJson(student);//對單個實例操做

//將對象的集合轉換成json字符串
String json=gson.toJson(arrayList);
System.out.println(json);

 


//解析json

//對單個實例操做

gson.fromJson(json,Sutdent.Class);//json爲要解析的字符串,Sutdent.Class爲對應的對象

//這裏生成的是一個實例集合
List<Student> arraylist=gson.fromJson(json, new TypeToken<List<Student>>(){}.getType());
for(Student stu:arraylist)
{
System.out.println(stu.name+" "+stu.sex);
}
}
}

class Student
{
String name;
String sex;
public Student(String name, String sex) {
super();
this.name = name;
this.sex = sex;
}

}

 

雖然使用JSONObject對象的方法也可以解析json字符串,可是顯然咱們這樣作,會更簡單

 

 

望不吝賜教!

相關文章
相關標籤/搜索