我使用gson库来解析json响应。它运作良好。现在我遇到了问题。
我收到了来自webservice的回复。 json键值不是静态的,它会动态变化。
如何编写解析器类来解析下面的响应。
格式化JSON :
{
"meta": {
"code": 201,
"dataPropertyName": "activity",
"currentTime": "2014-02-05 06:15:04",
"listedCount": "2"
},
"activity": [
{
"comments": [
{
"raja": {
"type": "Liked",
"userPhoto": "663.png",
"userId": "74",
"userName": {
"1_0": "longjump"
},
"postOwner": "you",
"postDetails": {
"471": {
"postImage": "972.png",
"postId": "471",
"postType": "1"
}
},
"dateTime": "2014-02-05 05:24:56",
"sameOwner": "1"
}
}
]
},
{
"follow": [
{
"you": {
"type": "follow",
"followByUserName": {
"0_0": "olivepop",
"1_0": "yadidroy",
"2_0": "chitra"
},
"followUserName": "you",
"followByUserPhoto": "242.png",
"followUserPhoto": "953.png",
"dateTime": "2014-01-09 06:50:42"
}
}
]
}
],
"notifications": [
"Activities has been retrieved successfully"
]
}
答案 0 :(得分:2)
使用此解析器类
Meta meta = new Meta();
ArrayList<Activity> activity = new ArrayList<ActivityParser.Activity>();
ArrayList<String> notifications = new ArrayList<String>();
public class Meta
{
String code,dataPropertyName,currentTime,listedCount;
}
public class Activity
{
ArrayList<HashMap<String, CommentsItem>> comments = new ArrayList<HashMap<String,CommentsItem>>();
public class CommentsItem
{
String type,userPhoto,userId,postOwner,dateTime,sameOwner;
HashMap<String, String> userName = new HashMap<String,String>();
HashMap<String, PostDetails> postDetails = new HashMap<String,PostDetails>();
public class PostDetails
{
String postImage,postId,postType;
}
}
ArrayList<HashMap<String, FollowItem>> follow = new ArrayList<HashMap<String,FollowItem>>();
public class FollowItem
{
String type,followUserName,followByUserPhoto,followUserPhoto,dateTime;
HashMap<String, String> followByUserName = new HashMap<String,String>();
}
}
答案 1 :(得分:0)
根据您的规范,您可以创建一个默认Web服务响应model.java,如下所示:
String success;
@SerializedName("error_msg")
String errorMessage;
@SerializedName("error_code")
String errorCode;
JsonObject data;
其中具有动态键的对象的父级将是“数据” 使用Gson,映射模型类:
webserviceResponse= gson.fromJson(contentResponse,WebserviceResponse.class);
if (StringUtils.isNotEmpty(webserviceResponse.getSuccess()) &&
StringUtils.equalsIgnoreCase(webserviceResponse.getSuccess(), "success")) {
//check for the dynamic key name
JsonObject job = webserviceResponse.getData();
dynamicallyDefinedKeyClass= gson.fromJson(job.get("dynamicKeyValue"), DynamicallyDefinedKeyClass.class);
}
如果可以帮助,将以任何方式编辑我的问题编辑答案 只是一个建议 - 拉贾,你等可以是一个关键名称或评论的价值观?你从哪里得到这个回复?
答案 2 :(得分:0)
如果可能的话,获取具有所有可能的“Key”值的JSON响应,然后从下面的链接获取POJO类自动构建:
它将自动处理所有可能性。但请确保您在生成POJO时提供的RESPONCE应保留您的Key的所有可能组合[更改一次]。
希望这有助于!!