[Android] Parsing JSON data with GSON

· 888 views

Translated by AI from 中文 · View original

This post was recovered from Internet Archive snapshots; some images may be lost.

Original JSON data

[
    {id:1,name:"酒吞童子",cv:"阪口周平"},
    {id:2,name:"茨木童子",cv:"福山润"},
    {id:3,name:"大天狗",cv:"前野智昭"},
    {id:4,name:"荒川之主",cv:"子安武人"}
]

Process

Adding the GSON dependency

compile 'com.google.code.gson:gson:2.2.4'

Creating the corresponding Java bean class

public class Shikigami{
        @SerializedName("id")// 为防止混淆后无法匹配
        public int id;
        @SerializedName("name")
        public String name;
        @SerializedName("cv")
        public String cv;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getCv() {
            return cv;
        }

        public void setCv(String cv) {
            this.cv = cv;
        }
    }

Parsing with Gson

//  解析JSON数据
Gson gson = new Gson();
List<Shikigami> shikigamiLists = gson.fromJson(json, new TypeToken<List<Shikigami>>() {}.getType());
// 取得数据
String name = shikigamiLists.get(index).name;
tring cv = shikigami.get(index).cv;

Release obfuscation settings

-dontwarn
# okhttp混淆配置
-keep class com.squareup.okhttp.** { *;}
-dontwarn com.squareup.okhttp.**
-dontwarn okio.**
# Gson混淆配置
-keepattributes Signature
-keepattributes *Annotation*
-keep class sun.misc.Unsafe { *; }
-keep class com.google.gson.stream.** { *; }
# Application classes that will be serialized/deserialized over Gson 下面替换成自己的实体类

All done!

Comments