java - 如何在android中使用GSON解析JSON

标签 java android json gson

我正在开发一个应用程序,我想在其中访问网络服务并获取数据。我正在使用 Google Volley 访问网络服务。我做得很好,但无法使用 GSON 解析 JSON 。我无法理解我哪里做错了。

Here is the URL of Web Services

这就是我正在做的事情

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
            Request.Method.GET,
            "https://api.github.com/repos/crashlytics/secureudid/issues",
            null,
            new MyListner(),
            new MyErrorListner()
    );

    requestQueue.add(jsonObjectRequest);

}

class MyListner implements Response.Listener<JSONObject>
{
    @Override
    public void onResponse(JSONObject response) {

        Gson gson = new Gson();
        Results results = gson.fromJson(response.toString(), Results.class);

        for(Test t : results.getmResults())
        {
            Log.e("Tag", t.toString());
        }


    }
}

class MyErrorListner implements Response.ErrorListener
{
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("Error", error.getMessage());
    }
}

下面给出了其他类

public class Results {


private ArrayList<Test> mResults;

public void setResults(ArrayList<Test> results)
{
    mResults = results;
}

public ArrayList<Test> getmResults()
{
    return mResults;
}
}

public class Test {

@SerializedName("title")
private String mTitle;

@SerializedName("user")
private User mUser;

@SerializedName("created_at")
private String mCreatedAt;

@SerializedName("body")
private String mBody;

@SerializedName("updated_at")
private String mUpdatedAt;

public String getmBody() {
    return mBody;
}

public void setmBody(String mBody) {
    this.mBody = mBody;
}

public String getmUpdatedAt() {
    return mUpdatedAt;
}

public void setmUpdatedAt(String mUpdatedAt) {
    this.mUpdatedAt = mUpdatedAt;
}

public String getmCreatedAt() {
    return mCreatedAt;
}

public void setmCreatedAt(String mCreatedAt) {
    this.mCreatedAt = mCreatedAt;
}

public User getmUser() {
    return mUser;
}

public void setmUser(User mUser) {
    this.mUser = mUser;
}

public String getmTitle() {
    return mTitle;
}

public void setmTitle(String mTitle) {
    this.mTitle = mTitle;
}

@Override
public String toString() {
    return mTitle + " " + mBody + " " + mCreatedAt + " " + mUpdatedAt + " " + mUser.getmLogin() + " ";
}
}


public class User {

@SerializedName("login")
private String mLogin;

public String getmLogin() {
    return mLogin;
}

public void setmLogin(String mLogin) {
    this.mLogin = mLogin;
}
}

这是我收到的错误

org.json.JSONException:  Value [{"url":"https:\/\/api.github.com\/repos\/crashlytics\/secureudid\/issues\/28","repository_url":"https:\/\/api.github.com\/repos\/crashlytics\/secureudid","labels_url":"https:\/\/api.github.com\/repos\/crashlytics\/secureudid\/issues\/28\/labels{\/name}","comments_url":"https:\/\/api.github.com\/repos\/crashlytics\/secureudid\/issues\/28\/comments","events_url":"https:\/\/api.github.com\/repos\/crashlytics\/secureudid\/issues\/28\/events","html_url":"https:\/\/github.com\/crashlytics\/secureudid\/pull\/28","id":222258999,"number":28,"title":"Fix broken headings in Markdown files","user":{"login":"bryant1410","id":3905501,"avatar_url":"https:\/\/avatars3.githubusercontent.com\/u\/3905501?v=4","gravatar_id":"","url":"https:\/\/api.github.com\/users\/bryant1410","html_url":"https:\/\/github.com\/bryant1410","followers_url":"https:\/\/api.github.com\/users\/bryant1410\/followers","following_url":"https:\/\/api.github.com\/users\/bryant1410\/following{\/other_user}","gists_url":"https:\/\/api.github.com\/users\/bryant1410\/gists{\/gist_id}","starred_url":"https:\/\/api.github.com\/users\/bryant1410\/starred{\/owner}{\/repo}","subscriptions_url":"https:\/\/api.github.com\/users\/bryant1410\/subscriptions","organizations_url":"https:\/\/api.github.com\/users\/bryant1410\/orgs","repos_url":"https:\/\/api.github.com\/users\/bryant1410\/repos","events_url":"https:\/\/api.github.com\/users\/bryant1410\/events{\/privacy}","received_events_url":"https:\/\/api.github.com\/users\/bryant1410\/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"assignees":[],"milestone":null,"comments":0,"created_at":"2017-04-17T23:26:47Z","updated_at":"2017-04-17T23:26:47Z","closed_at":null,"author_association":"NONE","pull_request":{"url":"https:\/\/api.github.com\/repos\/crashlytics\/secureudid\/pulls\/28","html_url":"https:\/\/github.com\/crashlytics\/secureudid\/pull\/28","diff_url":"https:\/\/github.com\/crashlytics\/secureudid\/pull\/28.diff","patch_url":"https:\/\/github.com\/crashlytics\/secureudid\/pull\/28.patch"},"body":"GitHub changed the way Markdown headings are parsed, so this change fixes it.\n\nSee [bryant1410\/readmesfix](https:\/\/github.com\/bryant1410\/readmesfix) for more information.\n\nTackles bryant1410\/readmesfix#1\n"},{"url":"https:\/\/api.github.com\/repos\/crashlytics\/secureudid\/issues\/13","repository_url":"https:\/\/api.github.com\/repos\/crashlytics\/secureudid","labels_url":"https:\/\/api.github.com\/repos\/crashlytics\/secureudid\/issues\/13\/labels{\/name}","comments_url":"https:\/\/api.github.com\/repos\/crashlytics\/secureudid\/issues\/13\/comments","events_url":"https:\/\/api.github.com\/repos\/crashlytics\/secureudid\/issues\/13\/events","html_url":"https:\/\/github.com\/crashlytics\/secureudid\/issues\/13","id":3923240,"number":13,"title":"Not working with ARC","user":{"login":"SaschaMoellering","id":1321549,"avatar_url":"https:\/\/avatars0.githubusercontent.com\/u\/1321549?v=4","gravatar_id":"","url":"https:\/\/api.github.com\/users\/SaschaMoellering","html_url":"https:\/\/github.com\/SaschaMoellering","followers_url":"https:\/\/api.github.com\/users\/SaschaMoellering\/followers","following_url":"https:\/\/api.github.com\/users\/SaschaMoellering\/following{\/other_user}","gists_url":"https:\/\/api.github.com\/users\/SaschaMoellering\/gists{\/gist_id}","starred_url":"https:\/\/api.github.com\/users\/SaschaMoellering\/starred{\/owner}{\/repo}","subscriptions_url":"https:\/\/api.github.com\/users\/SaschaMoellering\/subscriptions","organizations_url":"https:\/\/api.github.com\/users\/SaschaMoellering\/orgs","repos_url":"https:\/\/api.github.com\/users\/SaschaMoellering\/repos","events_url":"https:\/\/api.github.com\/users\/SaschaMoellering\/events{\/privacy}","received_events_url":"https:\/\/api.github.com\/users\/SaschaMoellering\/received_events","type":"User","site_admin":false},"labels":[],"state":"open","locked":false,"assignee":null,"assignees":[],"milestone":null,"comments":10,"created_at":"20

最佳答案

您正在尝试将对象数组(来自您的网络服务)解析为包含属性 mResults 的对象这是一个对象数组 ( Test );

而不是使用 Results解析期间您需要直接使用 ArrayList 类的Test :

Results results = gson.fromJson(response.toString(), Results.class);

应该是

ArrayList<Test> results = gson.fromJson(response.toString(), new TypeToken<ArrayList<Test>>(){}.getType());

由于 ArrayList 是一个泛型,它无法使用 ArrayList<Test>.class要获取数据类型的表示,我们必须使用 TypeToken 。什么是 TypeToken?

TypeToken represents a generic type T. Java doesn't yet provide a way to represent generic types, so this class does. Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.

getType返回用于构建 TypeToken 的类的类型,因此我们可以在 gson fromJson() 中使用它解析方法。

--

第二个问题:

您正在使用JsonObjectRequest但服务器响应是一个 Json 数组,因此您需要使用 JsonArrayRequest等等更新MyListner使用JSONArray而不是JSONObject

但是

当您手动解析服务器响应时,您可以使用 StringRequest因此避免解析Volley的步骤。

StringRequest jsonObjectRequest = new StringRequest(
    Request.Method.GET,
    "https://api.github.com/repos/crashlytics/secureudid/issues",
    new MyListner(),
    new MyErrorListner()
);

MyListner现在直接使用String :

class MyListner implements Response.Listener<String> {
    @Override
    public void onResponse(String response) {
        Gson gson = new Gson();
        ArrayList<Test> results = gson.fromJson(response, new TypeToken<ArrayList<Test>>() {}.getType());

        for (Test t : results) {
            Log.e("Tag", t.toString());
        }
    }
}

关于java - 如何在android中使用GSON解析JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46381020/

相关文章:

android - 如何垂直滚动图库的内容

java - android java消费vb.net wcf服务

java - 如何从代码而不是从我的 application-dev.yml、application-prod.yml 初始化属性

java - 这段从字符串方法解析为整数答案的代码可以吗?

java - 如何测试飞路迁移?

asp.net - 如何让 jqGrid 在后端使用 ASP.NET + JSON 工作?

javascript - 带有参数的函数值的 JSON

java - 在 xml 文件中为一个用户授予 spring security 访问权限

java - Android 版 OpenGL ES 2.0 中的纹理

c - 消息帕克 : How to compose an array of maps in msgpuck?