Java 使用Gson进行JSON解析,并给出null
我试图使用Gson解析JSON响应文档,但解析后它会给我一个空值 我的JSON响应是一个文档数组 Java代码Java 使用Gson进行JSON解析,并给出null,java,json,gson,Java,Json,Gson,我试图使用Gson解析JSON响应文档,但解析后它会给我一个空值 我的JSON响应是一个文档数组 Java代码 //Code to convert the response into JSON String res = gson.toJson(results); //Parse the JSON java.lang.reflect.Type collectionType = new TypeToken<List<Objects.JsonResponse>>()
//Code to convert the response into JSON
String res = gson.toJson(results);
//Parse the JSON
java.lang.reflect.Type collectionType = new TypeToken<List<Objects.JsonResponse>>() {}.getType();
List<Objects.JsonResponse> resp = gson.fromJson(res, collectionType);
System.out.println(resp.get(2).getName());
也许它给你空值是因为你把注释搞乱了 另外,从所有方法和字段中删除
static
,您正在尝试生成实例变量,而不是类变量
@SerializedName("product_id") // <---- not right
public String getName() { // <--- removed "static"
return name;
}
@SerializedName(“product_id”)/对象属性是静态的,您应该告诉GsonBuilder对其进行序列化
请按照此操作了解更多信息
更好的做法是不要将pojo类归档为静态:)这不是解决方案,更像是提示。我发现了你问题中的问题。问题在于json数组。如果删除所有数组和一个对象,这个问题就不会出现。我不知道你是否已经意识到这一点
请尝试以下json
{
“产品id”:“prod3400008”,
“创建日期”:“2011-02-17T00:00:00Z”,
“image_small”:“/hul_images/small/17_Rexona.jpg”,
“image_large”:“/hul_images/large/17_Rexona.jpg”,
“名称”:“小贝壳簇环耳环”,
“说明”:“小贝壳簇环耳环”,
“版本”:1527034576315089000
}
我移除了所有阵列
我还删除了类的静态声明JsonResponse
,以及所有成员变量的静态声明
这是您可以尝试的代码:
Gson-Gson=new-Gson();
String res=gson.toJson(结果);
JsonResponse=gson.fromJson(结果,JsonResponse.class);
System.out.println(response.product\u id);
System.out.println(response.create\u date)代码>
希望这将有助于解决问题。如果你还是找不到,让我知道。。。我会更加努力…:-) 谢谢你的回复。。但是我试着把它取下来。。但是没有成功,我不知道如何从响应中删除数组。你能给这个区域照点光吗!
[
{
"product_id": "prod3400008",
"create_date": "2011-02-17T00:00:00Z",
"image_small": "/hul_images/small/17_Rexona.jpg",
"image_large": "/hul_images/large/17_Rexona.jpg",
"name": "Small Shell Cluster Loop Earrings",
"description": "Small Shell Cluster Loop Earrings",
"tagline": [
"B1G1 75% Off Jewelry "
],
"category": [
"Earrings"
],
"catlevel0": [
"Accessories"
],
"catlevel1": [
"Jewelry"
],
"catlevel2": [
"Earrings"
],
"color": [
"Clearly Coral",
"Mocha Brown",
"Blue Lagoon",
"Hunter Green",
"Medium Purple"
],
"_version_": 1527034576315089000
}
]
@SerializedName("product_id") // <---- not right
public String getName() { // <--- removed "static"
return name;
}