Android的GSON反序列化到列表 [英] Android gson deserialization into list

查看:428
本文介绍了Android的GSON反序列化到列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图JSON字符串解析到一个列表或数组列表。我有以下的JSON响应,从我一个Android项目

创建了一个WCF RESTful服务来

  [
    {
        类:排版
        公司:存有
        ID:XXXX,
        名称:新安怡
    },
    {
        类:Consectetur
        公司:Adipiscing
        ID:YYYYY
        名称:法无
    }
]

我读过的若干个的就在这里解析GSON结果的例子,但我有困难,制定一个容器类,因为我已经看到了。我已经得到它读取一个结果成组类,但不能让它解析到任何种类的列表或ArrayList的。

组类:

 公共类组{    私人字符串ID;
    私人字符串名称;
    私人String类;
    私人字符串公司;
}

组容器类:

 公共类组{
    私人列表<组> GRP;
}

GSON解析的语句:

 组GRP = gson.fromJson(jsonString,Groups.class);

我也有做jsonString的一些处理,因为它显示与字符串(逗号之后)在某些空间了,它开始工作后,我把他们赶走,至少解析成一个单一的元素。不知道这影响什么,但想我会提到它。

另外,我试着做

键入listType =新TypeToken>(){} .getType();
gson.toJson(myStrings,listType);

但似乎并不要么工作,我不知道如果我的情况是必要的。


解决方案

 列表<组>组= gson.fromJson(jsonString,新TypeToken<名单,LT;组>>(){} .getType())

I am trying to parse a json string into a list, or arraylist. I have the following json response coming from a WCF RESTful service I created for an Android project

[
    {
        "Class": "Lorem",
        "Company": "Ipsum",
        "Id": "XXXX",
        "Name": "Avent"
    },
    {
        "Class": "Consectetur",
        "Company": "Adipiscing",
        "Id": "YYYYY",
        "Name": "Nulla"
    }
]

I've read several examples of parsing gson results on here, but I'm having difficulty enacting a container class as I've seen. I've gotten it to read a single result into a Group class, but cannot get it to parse into any kind of List or ArrayList.

Group Class:

public class Group {

    private String Id;
    private String Name;
    private String Class;
    private String Company;   
}

Group Container Class:

public class Groups {
    private List<Group> GRP;
}

gson parsing statement:

Groups GRP = gson.fromJson(jsonString, Groups.class);

I did have to do some manipulation of the jsonString because it was showing up with some spaces in the string (after the commas), and it started working after I removed them, at least for parsing into a single element. Not sure if that effects anything, but figured I'd mention it.

Also, I tried do the

Type listType = new TypeToken>() {}.getType(); gson.toJson(myStrings, listType);

but that doesn't seem to work either, and I didn't know if that is necessary for my situation.

解决方案

List<Group> groups = gson.fromJson(jsonString, new TypeToken<List<Group>>() {}.getType())

这篇关于Android的GSON反序列化到列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆