[英]Gson and arrays
I'm building a client server web application and stuck on this: 我正在构建客户端服务器Web应用程序,并坚持使用以下方法:
I'm getting an array of users "FriendsIDList:": 我收到了一系列用户“ FriendsIDList:”:
"data":{
"name":"anna",
"BirthDate":"2010-01-01",
"FriendsIDList":{
"email":"anna1@gmail.com",
"email":"anna2@gmail.com"
}
}}
Without the array I have no problem reading the data like this: 没有数组,我就不会像这样读取数据:
GsonBuilder gb = new GsonBuilder();
gb.setDateFormat("yyyy-MM-dd");
gson = gb.create();
newUser= gson.fromJson(data, user.class);
How can I read this array? 我如何读取此数组? I'm using LinkedList
in my user class: 我在用户类中使用LinkedList
:
LinkedList FriendsIDList;
In case you have a single user that contains the FriendList then your last line will work as you have mentioned. 如果您只有一个包含FriendList的用户,那么您的最后一行将如您所说的那样工作。
Try defining you FriendList property as follows: 尝试如下定义您的FriendList属性:
LinkedList<Email> FriendList;
And create Email Class: 并创建电子邮件类别:
public class Email {
private String email;
}
The JSON spec says this: JSON规范说:
A name is a string. 名称是一个字符串。 A single colon comes after each name, separating the name from the value. 每个名称后都有一个冒号,将名称与值分开。 A single comma separates a value from a following name. 单个逗号将值与后面的名称分开。 The names within an object SHOULD be unique. 对象中的名称应唯一。
Unfortunately Gson doesn't natively support non-unique names in name/value pairs. 不幸的是,Gson本身不支持名称/值对中的非唯一名称。 So it cannot properly handle your 'email' properties: 因此,它无法正确处理您的“电子邮件”属性:
{"email":"anna1@gmail.com","email":"anna2@gmail.com"}
You can work-around this by writing your own TypeAdapter . 您可以通过编写自己的TypeAdapter来解决此问题 。 Your implementation should accumulate email strings into a list. 您的实现应将电子邮件字符串累积到一个列表中。 You'll probably want to use a special wrapper object in your data model like EmailAddressList to make this easy. 您可能需要在数据模型中使用特殊的包装对象,例如EmailAddressList来简化此过程。
static class FriendsIDList {
List<String> emails;
}
static TypeAdapter<FriendsIDList> friendsIDListAdapter
= new TypeAdapter<FriendsIDList>() {
... // code to read and write emails
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.