在android中使用Gson api获取列表

时间:2014-01-30 08:00:27

标签: android gson

我知道如何使用JsonObject和JsonArray解析Json,现在我在android中解析Gson来解析Json

{Result:[
    {
    LanguageID: "1",
    LanguageName: "English",

    },
    {
    LanguageID: "2",
    LanguageName: "Tamil"
    },
    {
    LanguageID: "3",
    LanguageName: "Malayalam"
    },
    {
    LanguageID: "4",
    LanguageName: "Hindi"
    },
    {
    LanguageID: "5",
    LanguageName: "Telugu"
    }
    ]}

这是我的模型

public class GetLanguagesResult {

                    private String LanguageID;
                    private String LanguageName;



     GetLanguagesResult(String LanguageID,String LanguageName){

                        this.LanguageID=LanguageID;
                        this.LanguageName=LanguageName;

                    }

            public String getLanguageID(){

                        return LanguageID;

                    }

                    public String getLanguageName(){

                        return LanguageName;
                         }

                    }

有人可以告诉我如何使用模型类在ArrayList中获取LanguageID和LanguageName。

2 个答案:

答案 0 :(得分:1)

尝试以下课程代码。

public class Response {

    ArrayList<Result> Result;

    public class Result {
        String LanguageID;
        String LanguageName;

        public String getLanguageID() {
            return LanguageID;
        }

        public void setLanguageID(String languageID) {
            LanguageID = languageID;
        }

        public String getLanguageName() {
            return LanguageName;
        }

        public void setLanguageName(String languageName) {
            LanguageName = languageName;
        }
    }
}

使用

ArrayList<Result> results = gson.fromJson(jsonResponse, Response.Class);

答案 1 :(得分:1)

你必须创建另一个只包含一个名为 Result 类型的属性的类,其中包含getter和setter。

public class Results {
    private List<GetLanguagesResult> Result;

    public Result getResult(){
        return Result;
    }

    public void setResult(List<GetLanguagesResult> Result){
        this.Result = Result;
    }

}

然后你可以用这种方式反序列化它:

Results results = g1.fromJson(myDownloadedJson, Results.Class);