1. 程式人生 > >Gson轉換json數據為對象

Gson轉換json數據為對象

大量 () .get 轉換問題 兩種方法 json數據 pos des on()

可以通過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這種封裝對象的方式,如果僅僅是取某值的話,可以采用這種方式,可以節約大量時間

技術分享圖片

Gson轉換json數據為對象