我知道JSONArray
和JSONObject
之间的区别。
我对它们的反序列化有疑问。
当反序列化对象数组类型Cluster
时,我可以使用fromJson
对象进行操作。相反地,当反序列化类型为Topic
的对象时,我不得不使用JSONParser
。
它们之间有什么区别?我无法确定何时使用JSONParser
。
附:Cluster
类:
package com.example.android_json;
public class Cluster {
public String title;
public String stories;
public String src;
public Cluster()
{
}
public Cluster(String title,String stories,String src)
{
this.title = title;
this.stories = stories;
this.src = src;
}
}
Topic
类:
package com.example.news_android_mobile_application_cd;
import java.util.ArrayList;
import java.util.List;
import checkdeck.news.ui_services_java_api.rest.model.MiniCluster;
public class Topic {
public Topic()
{
}
public Topic(String TopicID,String TopicName,ArrayList<MiniCluster> miniCluster,ArrayList<String> clusterid)
{
topicName = TopicName;
topicID = TopicID;
clusterList = miniCluster;
clusterID = clusterid;
}
String topicID;
String topicName;
boolean isMandatory;
List<MiniCluster> clusterList = new ArrayList<MiniCluster>();
ArrayList<String> clusterID = new ArrayList<String>();
}
以下是反序列化代码:
对于集群类(Cluster class):
Gson gson1 = new Gson();
Cluster[] clusters = gson1.fromJson(json, Cluster[].class);
对于Topic类:
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonObject responseObj = parser.parse(json).getAsJsonObject();
String topicID = responseObj.getAsJsonPrimitive("topicID").getAsString();
String topicName = responseObj.getAsJsonPrimitive("topicName").getAsString();
Boolean isMandatory = responseObj.getAsJsonPrimitive("isMandatory").getAsBoolean();
JsonArray cList = responseObj.getAsJsonArray("clusterList");
JsonArray cID = responseObj.getAsJsonArray("clusterID");
List<MiniCluster> clusterList = new ArrayList<MiniCluster>();
ArrayList<String> clusterID = new ArrayList<String>();
for(int i=0;i<cID.size();i++)
{
clusterList.add(gson.fromJson(cList.get(i), MiniCluster.class));
clusterID.add(cID.get(i).toString());
}
需要反序列化的JsonData
提前致谢。