【问题标题】:Deserialization of JSON webservice in AndroidAndroid中JSON webservice的反序列化
【发布时间】:2012-03-28 10:23:03
【问题描述】:

我正在尝试将此 JSON 数组反序列化到我的 android 项目中。

[{"Name":"Ban","Price":1},{"Name":"Banana","Price":1},{"Name":"chicken","Price":14},{"Name":"pizza","Price":16},{"Name":"slice","Price":1}]

我在 Asp.net 中创建了这个 web 服务。 我用来反序列化它的代码在下面

public void onClick(View v)
{
    String url="http://192.168.15.2/MyAndroid/InputCaller.aspx"; //do not use localhost
    String response=callWebService(url);

    List<Items> mObjectList =  new ArrayList<Items>() ;
    ItemsList list = null;
    Gson gson = new Gson();
    list = gson.fromJson(response, ItemsList.class);
    // list = getItemsList(response);
    Intent myIntent = new Intent(v.getContext(), Cart.class);
    startActivity(myIntent);    
}

public final ItemsList getItemsList (String jsonString)
{
    ItemsList il = null;
    Gson gson = new Gson();
    il = gson.fromJson(jsonString, ItemsList.class);
    return il;
}

public class ItemsList
{
    private List<ItemsContainer> items = new ArrayList<ItemsContainer>();

    public List<ItemsContainer> getItemsContainerList()
    {
        return items;
    }
}

class ItemsContainer
{
    Items items;
    public Items getItem()
    {
        return items;
    }
}

public class Items
{
    String Name;
    int Price;
}

它不起作用,当我尝试调试它时,我在 list = gson.fromJson(response, ItemsList.class); 上收到此消息 未找到 Gson.class 源。 这是我的第一个反序列化程序,如果有人帮助我,我将不胜感激。谢谢,

【问题讨论】:

    标签: android web-services json.net deserialization


    【解决方案1】:

    不要通过为 Items 类使用更多的父类(作为容器)来使事情变得复杂。只需使用 Gson 将所有项目反序列化为 List 对象,如下所示:

    List<Items> listItems = (List<Items>) gson.fromJson(response,
                                           new TypeToken<List<Items>>(){}.getType());
    

    现在您已经获得了 List 对象中的所有项目:listItems

    【讨论】:

    • Waqas 成功了,我会在期限结束后将其标记为答案。谢谢,我想将此数据转移到一个新活动中并希望将其显示在一个列表中。你能给我一个粗略的草图吗?如何完成。
    • 这很简单。使用 Intent.putExtra("json", "all the json string"); 将您的 json 字符串传递给另一个活动,并在接收活动时,将 json 字符串检索为 String strJson = getIntent().getExtras().getString("json");,然后使用该 strJson 使用我的回答中的技术重建项目的列表对象跨度>
    猜你喜欢
    • 1970-01-01
    • 2013-02-18
    • 2011-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多