1. 程式人生 > >Gson轉換json資料為物件

Gson轉換json資料為物件

可以通過Gson使用兩種方法,將json字串轉換為物件,以下面該段報文做測試

{
    "id": 84041462,
    "lastName": "小華",
    "age":32,
    "balance":666255.32,
    "hobbyDesc": {
        "subject": "數學",
        "score":25,
        "sport_desc":"跑步有益健康"
    }    
}

1. 建立實體類,通過 fromJson方法將json資料封裝進物件中

如上,將上面報文按層次解析並建立兩個物件

import com.google.gson.annotations.SerializedName;

public class HobbyDesc {

    private String subject;
    private int score;
    @SerializedName("sport_desc")
    private String sportDesc;

    //***
public class Account {
    private String id;
    private String lastName;
    
private int age; private double balance; private HobbyDesc hobbyDesc;
//
***

解析

String jsonStr = "{\n" +
                "\t\"id\": 84041462,\n" +
                "\t\"lastName\": \"小華\",\n" +
                "\t\"age\":32,\n" +
                "\t\"balance\":666255.32,\n" +
                "\t\"hobbyDesc\": {\n" +
                "\t\t\"subject\": \"數學\",\n" +
                "\t\t\"score\":25,\n" +
                "\t\t\"sport_desc\":\"跑步有益健康\"\n" +
                "\t}\n" +
                "\t\n" +
                "}";

Account account 
= new Gson().fromJson(jsonStr,Account.class);

同時也可以看到,物件中定義為字串型別的欄位也可以接受json串的數值型別,沒有轉換問題。

2. 解析為jsonObject物件

直接使用Gson API解析

String jsonStr = "{\n" +
                "\t\"id\": 84041462,\n" +
                "\t\"lastName\": \"小華\",\n" +
                "\t\"age\":32,\n" +
                "\t\"balance\":666255.32,\n" +
                "\t\"hobbyDesc\": {\n" +
                "\t\t\"subject\": \"數學\",\n" +
                "\t\t\"score\":25,\n" +
                "\t\t\"sport_desc\":\"跑步有益健康\"\n" +
                "\t}\n" +
                "\t\n" +
                "}";
JsonObject jsonObject = (JsonObject) new JsonParser().parse(jsonStr); 
System.out.println(
"id <getAsInt> = "+jsonObject.get("id").getAsInt());//id <getAsInt> = 84041462 System.out.println("id <getAsString> = "+jsonObject.get("id").getAsString());//id <getAsString> = 84041462 System.out.println("position = "+ jsonObject.get("hobbyDesc").getAsJsonObject().get("sport_desc").getAsString());//position = 跑步有益健康

參照jsonObject結構,可以瞭解Gson這種封裝物件的方式,如果僅僅是取某值的話,可以採用這種方式,可以節約大量時間