我在解析java中的json数组时遇到了麻烦。
我有一个JSON数组,如下所示从服务器返回
[
{
"User": "538000001",
"Transaction-Id": "oHbgP2y2OXfdDcxAOI/q9HxY68PNs+xS+8CvfGpoN2ZUU/8mavBaI0564VeZXYBDMnk84kkfZeCJM51I92rFdf4Zi4uKEoqJd7jr78bXo4MOyoSs5mntIir7aVJ9/b+4nz6x2+g0LPY7+Sq8RHvbr+c4Evhg+VXeKDzE3f6+bJo=,YWFhd3MxLnJlYWxtMTsxNDE4MDczNTk0MjkxOzUyQDUzODAwMDAwMQ==",
"Challenge-Response": "7ZGlkpVfYvQDjvTa2EShZwZ3dGc=",
"Challenge": "MzcrMzM3NzA4MTM3KzE0MTgwNzM1OTQ="
},
{
"User": "538000000",
"Transaction-Id": "+5Oi4NnG9HOVMPx4nM/TP4ZBONG4HtOBbA5+uf/d+hik7o1Aes9H0PLCqAgG/Td2xLDPOdZJJW7ppj3MLkZBvJr+t9JWKdSGpGHAYTp0oonRTVsesPVCtNI6dXvMY9P+bHDiBWkZiqjSjOZuuzImLaJ17G1/D/GNqIonaNCjqjo=,YWFhd3MxLnJlYWxtMTsxNDE4MDczNTk0Mjk1OzUzQDUzODAwMDAwMA==",
"Challenge-Response": "eEzLzYLmzo5R2tNwokG0mfbuLZY=",
"Challenge": "MzgrNDY2NjY4NjgyKzE0MTgwNzM1OTQ="
}
]
我使用GSON来解析这个数组,但到目前为止还不成功。我写了下面的代码
class round1Body
{
String User;
String Transaction_Id;
String Challenge_Response;
String Challenge;
round1Body(String User,String Transaction_Id,String Challenge_Response,String Challenge)
{
this.User = User;
this.Transaction_Id=Transaction_Id;
this.Challenge_Response = Challenge_Response;
this.Challenge=Challenge;
}
@Override
public String toString()
{
return "User = " + User + " Transaction-Id = " + Transaction_Id + " Challenge-Response = " + Challenge_Response + "Challenge = "
+ Challenge;
}
}
Type listType = new TypeToken<ArrayList<round1Body>>(){}.getType();
Object jsonE = new Gson().fromJson(firstResponse.readEntity(String.class),listType);
System.out.println(jsonE);
我尝试打印时的输出是[null,null]。
有人可以帮帮我吗?
提前致谢!
答案 0 :(得分:1)
您似乎对firstResponse.readEntity(String.class)
电话有疑问。否则你不会有[null, null]
作为输出。所以问题首先来自这里。试着让它发挥作用。
然后,如果你没有在你的课程中指定SerializedName
规则&#39;字段,GSON要求名称必须与JSON文件中的密钥名称完全匹配。
您在JSON端有"Transaction-Id"
但在Java文件中将其定义为Transaction_Id
,Challenge_Response
也是如此。
由于在Java中标识符不能有-
,因此您需要为这两个属性指定规则。
class round1Body {
String User;
@SerializedName("Transaction-Id")
String Transaction_Id;
@SerializedName("Challenge-Response")
String Challenge_Response;
String Challenge;
//...
}
通过这些更改,它成功打印(我正在从文件中读取您的JSON字符串):
[User = 538000001 Transaction-Id = oHbgP2y2OXfdDcxAOI/q9HxY68PNs+xS+8CvfGpoN2ZUU/8mavBaI0564VeZXYBDMnk84kkfZeCJM51I92rFdf4Zi4uKEoqJd7jr78bXo4MOyoSs5mntIir7aVJ9/b+4nz6x2+g0LPY7+Sq8RHvbr+c4Evhg+VXeKDzE3f6+bJo=,YWFhd3MxLnJlYWxtMTsxNDE4MDczNTk0MjkxOzUyQDUzODAwMDAwMQ== Challenge-Response = 7ZGlkpVfYvQDjvTa2EShZwZ3dGc=Challenge = MzcrMzM3NzA4MTM3KzE0MTgwNzM1OTQ=, User = 538000000 Transaction-Id = +5Oi4NnG9HOVMPx4nM/TP4ZBONG4HtOBbA5+uf/d+hik7o1Aes9H0PLCqAgG/Td2xLDPOdZJJW7ppj3MLkZBvJr+t9JWKdSGpGHAYTp0oonRTVsesPVCtNI6dXvMY9P+bHDiBWkZiqjSjOZuuzImLaJ17G1/D/GNqIonaNCjqjo=,YWFhd3MxLnJlYWxtMTsxNDE4MDczNTk0Mjk1OzUzQDUzODAwMDAwMA== Challenge-Response = eEzLzYLmzo5R2tNwokG0mfbuLZY=Challenge = MzgrNDY2NjY4NjgyKzE0MTgwNzM1OTQ=]
请注意,您可以使用此批注来遵守命名约定。