JSONArray
我知道和之间的区别JSONObject
。
我对反序列化它们有疑问。
在反序列化对象类型数组时Cluster
,我可以使用fromJson
object. 相反,在反序列化类型对象时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>();
}
反序列化代码如下 -
对于集群类:
Gson gson1 = new Gson();
Cluster[] clusters = gson1.fromJson(json, Cluster[].class);
对于主题类:
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());
}
提前致谢。