我有一个像这样的JSON字符串:
{
"response":[2,
{
"id":"187",
"name":"John",
"surname":"Corner"
},
{
"id":"254",
"name":"Bob",
"surname":"Marley"
}
]
}
如何使用Java中的GSON lib解析它? 我试过了:
static class SearchRequest {
private Names[] response;
static class Names {
private int id;
private String name;
private String surname;
}
}
但它不起作用:(
答案 0 :(得分:2)
response
数组不仅包含Names
,还包含整数值:response[0]=2
。
所以你必须使用像
private Object[] response;
添加:强>
我认为,您无需更改JSON,因为您的response
是私有的,因此您应该使用getter:
static class SearchRequest {
private Object[] response;
static class Names {
private int id;
private String name;
private String surname;
}
public List<Names> getNames() {
List list = new ArrayList();
list.addAll(Arrays.asList(response));
return (List<Names>) list.subList(1, response.length);
}
public int getAmount() {
return (Integer) response[0];
}
public void setNames(List<Names> names) {
response = new Object[names.size() + 1];
response[0] = names.size();
for (int i = 0, namesSize = names.size(); i < namesSize; i++) {
response[i + 1] = names.get(i);
}
}
}
答案 1 :(得分:1)
我准备了一个用于测试案例的示例代码,使用gson-2.1.jar
作为库并正确运行它。我通过从 response 数组的开头删除"2,"
来修改您的JSON字符串,因为它导致异常。看看并测试这段代码:
import com.google.gson.Gson;
public class Test
{
static class SearchRequest
{
private Names [] response;
static class Names
{
private int id;
private String name;
private String surname;
}
}
public static void main ( String [] args )
{
Gson gson = new Gson();
String str = "{ \"response\":"
+ "[{\"id\":\"187\",\"name\":\"John\",\"surname\":\"Corner\"},"
+ "{\"id\":\"254\",\"name\":\"Bob\",\"surname\":\"Marley\"}]}";
SearchRequest request = new SearchRequest();
request = gson.fromJson( str, SearchRequest.class );
System.out.println( "name of 1st: " + request.response [ 0 ].name );
System.out.println( "surname of 2nd: " + request.response [ 1 ].surname );
}
}
输出:
name of 1st: John
surname of 2nd: Marley