将JSON转换为Java类(从Android应用程序调用WebApi)

时间:2016-04-25 19:26:07

标签: java c# android json

我正在研究我的学校项目,并且刚开始学习android编程,但我在c#和.net中有一些编程经验。

这是我的代码:

    public class ProizvodiAPI {

    public class ProizvodiVM implements Serializable
    {
        public Integer proizvodID;
        public String naziv;
        public String sifra;
        public BigDecimal cijena;
        public String jedinicaMjere;
        public String vrstaProizvoda;
    }
        public class ProizvodiLista implements Serializable
        {
            public  List<ProizvodiVM> proizvodi;
        }
public static void GetAllProizvode(final MyRunnable<ProizvodiLista> onSuccess)
    {

        RequestQueue queue = Volley.newRequestQueue(MyApp.getContext());
        String url = "Proizvodi/GetProizvodiVM";

        // Request a string response from the provided URL.
        StringRequest stringRequest = new StringRequest(Request.Method.GET, Config.urlApi + url,
                new Response.Listener<String>()
                {
                    @Override
                    public void onResponse(String response)
                    {
                        final Gson gson = MyGson.build();
                        final ProizvodiLista model = gson.fromJson(response, ProizvodiLista.class);
                        onSuccess.run(model);
                    }
                }, new Response.ErrorListener()
        {
            @Override
            public void onErrorResponse(VolleyError error)
            {

                Toast.makeText(MyApp.getContext() , "That didn't work", Toast.LENGTH_LONG).show();
            }
        });
        // Add the request to the RequestQueue.
        queue.add(stringRequest);
    }
}

程序在这里崩溃:

final ProizvodiLista model = gson.fromJson(response, ProizvodiLista.class);

反序列化json的问题是,如果是的话,我应该更改Java类以及要更改的内容吗?

这是Web Api中的C#类:

public class Proizvodi
    {
        public int ProizvodID { get; set; }
        public string Naziv { get; set; }
        public string Sifra { get; set; }
        public decimal Cijena { get; set; }

        public string JedinicaMjere { get; set; }
        public string VrstaProizvoda { get; set; }
    }

这是回应: json response

1 个答案:

答案 0 :(得分:1)

在不知道崩溃原因的情况下,我最好的猜测是你创建一个类只是为了包装一个列表而且可能导致崩溃。 使用包装器类,您的json应该有一个与列表对象名称匹配的键,该值将是一个json数组。

要反序列化json数组,请检查this answer

还可以尝试在ProizvodiVM中使用@SerializedName注释。这样您就可以正确映射json键字段。