需要一些帮助,使用Gson + Volley绑定一个模型。

问题描述 投票:0回答:1

我在Android和Volley中绑定json到模型时遇到了一些麻烦。

我的JSON看起来是这样的。https:/raw.githubusercontent.comZungatePokemonJSONmasterpokedex.json。

我的Model是这样的。

public class Pokemon
{
private int number;
private String name;
private String type1;
private String type2;
private String imageName;

public Pokemon()
{
}

public Pokemon(int number, String name, String type1, String type2, String imageName)
{
    this.number = number;
    this.name = name;
    this.type1 = type1;
    this.type2 = type2;
    this.imageName = imageName;
}
... Getters not included for brevity
}

我的Volley和JSON尝试。

String url = "https:/raw.githubusercontent.comZungatePokemonJSONmasterpokedex.json。";

    RequestQueue queue = Volley.newRequestQueue(getActivity().getApplicationContext());

    final StringBuilder sb = new StringBuilder();

    StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
            new Response.Listener<String>()
            {
                @Override
                public void onResponse(String response)
                {
                    Log.d("response", response);

                    Gson gson = new Gson();
                    //List<Pokemon> pokemonList = gson.fromJson(response, new TypeToken<List<Pokemon>>() {}.getType());
                    Pokemon[] pokemonList = gson.fromJson(response, Pokemon[].class);
                    //Log.d("Pokemon", ""+ pokemonList.get(0));
                    Log.d("Pokemon", "Name: "+ pokemonList[0].getName());

                }
            },
            new Response.ErrorListener()
            {
                @Override
                public void onErrorResponse(VolleyError error)
                {
                    error.printStackTrace();
                }
            }
    );

    queue.add(stringRequest);

这些注释行是我也试过的,也没有用。可能是我漏掉了一些明显的东西,但是我看了这么久,就是不知道了。

回复是正确的,pokemonLIst对象正确有1889个物品。但是每个物品的属性都是空的或者0。

我到底做错了什么?

android json gson android-volley
1个回答
0
投票

在许多灰发之后找到了答案。

它是大小写敏感的,所以我通过添加这个来固定它。

@SerializedName("NameOfAttribute")到Pokemon.java的每个相关字段中去

© www.soinside.com 2019 - 2024. All rights reserved.