如何从 JSON 字符串中获取数据?
我有一个像这样的 JSON 字符串:
{
"response":[2,
{
"id":"187",
"name":"John",
"surname":"Corner"
},
{
"id":"254",
"name":"Bob",
"surname":"Marley"
}
]
}
How can I parse it using GSON lib in Java? 我尝试过:
static class SearchRequest {
private Names[] response;
static class Names {
private int id;
private String name;
private String surname;
}
}
但不起作用:(
I have a JSON string like this:
{
"response":[2,
{
"id":"187",
"name":"John",
"surname":"Corner"
},
{
"id":"254",
"name":"Bob",
"surname":"Marley"
}
]
}
How can I parse it using GSON lib in Java?
I tried:
static class SearchRequest {
private Names[] response;
static class Names {
private int id;
private String name;
private String surname;
}
}
but it doesn't works :(
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
response
数组不仅包含Names
,还包含一个整数值:response[0]=2
。所以你必须使用类似
ADD: 的东西
我认为,您无需更改 JSON,因为您的
response
是私有的,因此您应该使用 getter:response
array contains not onlyNames
, it also contains an integer value:response[0]=2
.So you must use something like
ADD:
I think, you have no need to change your JSON, because your
response
is private, so you should use getters:我准备了一个示例代码来测试您的案例,使用
gson-2.1.jar
作为库并正确运行它。我通过从 response 数组的开头删除"2,"
来修改您的 JSON 字符串,因为它导致了异常。查看并测试此代码:输出:
I prepared a sample code for testing your case, used
gson-2.1.jar
as library and run it correctly. I modified your JSON string by removing"2,"
from the beginning of response array since it caused exceptions. Take a look at and test this code:Output: