如何使用JSON和GSON

james發表於2017-11-01

說明:本專案是在MyEclipse中建立Maven專案來進行對於json格式檔案的操作

  在maven專案中引入對於支援json開發的的依賴,在pom.xml檔案中新增一下依賴:
      <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20090211</version>
      </dependency>
                       

1. JSON使用指南

**使用jsonobject的原生的方法生成一個jsonobject**

———-

<1>建立一個jsonobject物件
   JSONObject wamgxiaoer = new JSONObject();
<2>使用鍵值對對的形式新增物件的一些屬性
  
    Object nullobj = null;
    wamgxiaoer.put("name", "王小二");
    wamgxiaoer.put("age", 25.2);
    wamgxiaoer.put("birthday", "1990-01-01");
    wamgxiaoer.put("schooll", "藍翔");
    wamgxiaoer.put("major",new String[]{"理髮","挖掘機"});
    wamgxiaoer.put("has_girfriend", false);
    wamgxiaoer.put("car", nullobj);
    wamgxiaoer.put("house", nullobj);    
    wamgxiaoer.put("comment", "這是一個註釋");

//使用tostring方法將json格式的資料轉化成一個string型別的資料進行輸出

    System.out.println(wamgxiaoer.toString());

使用Map方式生成jsonobject物件

<1>生成一個map型別的物件
Map<String, Object> wamgxiaoer = new HashMap<String, Object>();

  Object nullobj = null;
    wamgxiaoer.put("name", "王小二");
    wamgxiaoer.put("age", 25.2);
    wamgxiaoer.put("birthday", "1990-01-01");
    wamgxiaoer.put("schooll", "藍翔");
    wamgxiaoer.put("major",new String[]{"理髮","挖掘機"});
    wamgxiaoer.put("has_girfriend", false);
    wamgxiaoer.put("car", nullobj);
    wamgxiaoer.put("house", nullobj);    
    wamgxiaoer.put("comment", "這是一個註釋");

使用jsonobject的tomap方法講一個map型別的物件轉換成一個jsonobject物件,最後利用jsonobject物件的tostring方法轉換成一個字元型別資料
System.out.println(new JSONObject(wamgxiaoer).toString());

使用Java Bean方法構建json

<1>建立一個Java bean

 package bean;
import java.util.Arrays;  
import com.google.gson.annotations.SerializedName; 
public class Diaosi {

//    @SerializedName("NAME")
    private String name;
    private String school;
    private boolean has_girlfriend;
    private double age;
    private Object car;
    private Object house;
    private String[] major;
    private String coment;
    private String birthday;
    private transient String ignore;
        
    public String getIgnore() {
        return ignore;
    }
    public void setIgnore(String ignore) {
        this.ignore = ignore;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getSchool() {
        return school;
    }
    public void setSchool(String school) {
        this.school = school;
    }
    public boolean isHas_girlfriend() {
        return has_girlfriend;
    }
    public void setHas_girlfriend(boolean has_girlfriend) {
        this.has_girlfriend = has_girlfriend;
    }
    public double getAge() {
        return age;
    }
    public void setAge(double age) {
        this.age = age;
    }
    public Object getCar() {
        return car;
    }
    public void setCar(Object car) {
        this.car = car;
    }
    public Object getHouse() {
        return house;
    }
    public void setHouse(Object house) {
        this.house = house;
    }
    public String[] getMajor() {
        return major;
    }
    public void setMajor(String[] major) {
        this.major = major;
    }
    public String getComent() {
        return coment;
    }
    public void setComent(String coment) {
        this.coment = coment;
    }
    public String getBirthday() {
        return birthday;
    }
    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }
    @Override
    public String toString() {
        return "Diaosi [name=" + name + ", school=" + school + ", has_girlfriend=" + has_girlfriend + ", age=" + age
                + ", car=" + car + ", house=" + house + ", major=" + Arrays.toString(major) + ", coment=" + coment
                + ", birthday=" + birthday + "]";
    }    
}

<2>使用自己建立的Java bean的方法來設定屬性

 private static void creatByJavaBean() {
        Diaosi wamgxiaoer = new Diaosi();
        wamgxiaoer.setName("王小二");
        wamgxiaoer.setAge(25.2);
        wamgxiaoer.setBirthday("1990-01-01");
        wamgxiaoer.setSchool("藍翔");
        wamgxiaoer.setMajor(new String[]{"理髮","挖掘機"});
        wamgxiaoer.setHas_girlfriend(false);
        wamgxiaoer.setCar(null);
        wamgxiaoer.setHouse(null);
        wamgxiaoer.setComent("這是一個註釋");
        System.out.println(new JSONObject(wamgxiaoer));
    }

從檔案解析json物件
<1>首先在pom.xml檔案引入Commons-io來使用一些對於檔案的操作,例如:

<dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
    </dependency>
    

<2>獲取json檔案所在的路徑從而獲取一個檔案物件

File file = new File(ReadJsonSample.class.getResource("/wangxiaoer.json").getFile());  

<3>獲取檔案中的內容:
String content = FileUtils.readFileToString(file);
<4>建立一個jsonobject物件來解析json格式的資料
JSONObject jsonObject = new JSONObject(content);
<5>通過json的方法來獲取一些屬性對於的值

if(!jsonObject.isNull("name")){
            System.out.println("姓名是:"+jsonObject.getString("name"));
        }  
        if(!jsonObject.isNull("nickname")){
            System.out.println("姓名是:"+jsonObject.getString("nickname"));
        } 
        System.out.println("年齡是:"+jsonObject.getDouble("age"));
        System.out.println("是否有女朋友:"+jsonObject.getBoolean("has_girlfriend"));
        JSONArray majorArray =  jsonObject.getJSONArray("major");
        for(int i = 0;i<majorArray.length();i++){
            String m = (String)majorArray.get(i);
            System.out.println("專業-"+(i+1)+":"+m);
        }

2..GSON使用指南
GSON是由谷歌公司提出來的出來json格式資料的方法
<2>引入關於GSON的依賴

 <dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>

<3>建立一個類的例項併為其賦值

Diaosi wamgxiaoer = new Diaosi();

wamgxiaoer.setName("王小二");
wamgxiaoer.setAge(25.2);
wamgxiaoer.setBirthday("1990-01-01");
wamgxiaoer.setSchool("藍翔");
wamgxiaoer.setMajor(new String[]{"理髮","挖掘機"});
wamgxiaoer.setHas_girlfriend(false);
wamgxiaoer.setCar(null);
wamgxiaoer.setHouse(null);
wamgxiaoer.setComent("這是一個註釋");
wamgxiaoer.setIgnore("不要看見我!");

<4>建立一個GSON物件
Gson gson = new Gson();
<5>使用GSON物件的tostring方法將其轉換成一個string型別的物件
System.out.println(gson.toJson(wamgxiaoer));
<6>GSONbuilder建立個性化的json格式的資料,並通過gsonbuilder的create方法來建立一個gson物件

GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();
    gsonBuilder.setFieldNamingStrategy(new FieldNamingStrategy() {          
        public String translateName(Field f) {
            
            if(f.getName().equals("name")){
                return "NAME";
            }
            return f.getName();
        }
    });
    Gson gson = gsonBuilder.create();
    System.out.println(gson.toJson(wamgxiaoer));
}

GSON解析json格式資料
<1>獲取json的資料檔案內容

File file = new File(ReadJsonSample.class.getResource("/wangxiaoer.json").getFile());
        String content = FileUtils.readFileToString(file);            

<2>建立一個GSON物件

 Gson gson =new  GsonBuilder().setDateFormat("yyyy-MM-dd").create();

<3>使用GSON進行反解析

Gson gson =new GsonBuilder().setDateFormat(“yyyy-MM-dd”).create();

DiaosiWithBirthday wangxiaoer = gson.fromJson(content, DiaosiWithBirthday.class);
System.out.println(wangxiaoer.getBirthday().toLocaleString());
System.out.println(wangxiaoer.getMajor());
System.out.println(wangxiaoer.getMajor().getClass());

想了解更多關於GSON的可以在GitHub上檢視GSON的官方文件,最後附上專案的下載地址:
連結:http://pan.baidu.com/s/1pLHp5ph 密碼:khbb

相關文章