【问题标题】:Need some help binding a model using Gson + Volley需要帮助使用 Gson + Volley 绑定模型
【发布时间】:2020-09-30 03:35:47
【问题描述】:

我在将 json 绑定到 Android 和 Volley 中的模型时遇到了一些问题。

我的 JSON 如下所示: https://raw.githubusercontent.com/Zungate/PokemonJSON/master/pokedex.json

我的模型如下所示:

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 尝试:

字符串 url = "https://raw.githubusercontent.com/Zungate/PokemonJSON/master/pokedex.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 个项目。然而,每个项目的属性都是 null 或 0。

我做错了什么?

【问题讨论】:

    标签: android json gson android-volley


    【解决方案1】:

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

    它区分大小写,所以我通过添加以下内容来修复它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      • 2019-07-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多