Android 如何从一个JSON响应中分割两个对象的数据?
我从服务器得到json响应…但它包含两个对象的数据…一个是ArrayList类型,第二个是POJO(HomeVO)类。我想将数据拆分并存储到不同的对象中。我是usnig GSON apiAndroid 如何从一个JSON响应中分割两个对象的数据?,android,json,servlets,gson,Android,Json,Servlets,Gson,我从服务器得到json响应…但它包含两个对象的数据…一个是ArrayList类型,第二个是POJO(HomeVO)类。我想将数据拆分并存储到不同的对象中。我是usnig GSON api Servlet: response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(new Gson()
Servlet:
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(questions));
response.getWriter().write(new Gson().toJson(homeVo));
Json Response:
[{"questionId":2,"question":"Quality","typeOfQuestion":2}, {"questionId":3,"question":"Satisfaction","typeOfQuestion":1},{"questionId":4,"question":"overall","typeOfQuestion":2}]{"feedbackName":"IMS","expiryDate":"2014-12-12","createdDate":"2014-10-24","feedbackId":2}
Android Parsing:
HttpClient httpClient = WebServiceUtils.getHttpClient();
try {
HttpResponse response = httpClient.execute(new HttpGet(url));
HttpEntity entity = response.getEntity();
Reader reader = new InputStreamReader(entity.getContent());
data = gson.fromJson(reader, arrayListType);
} catch (Exception e) {
e.printStackTrace();
Log.i("json array",
"While getting server response server generate error. ");
}
我相信你们有两个POJO的问题和HomeVO课程。然后按照以下步骤操作: 您可以使用两个列表(问题和homeVo)创建另一个DTO
公共类ResultDTO{
私人列表homeVoList;
私人列表<问题>问题列表;
//在此处使用您的getter和setter:
}
您有两种选择:
1.手动解析字符串(不推荐使用)
2.使用Gson将JSon对象转换为对象,然后使用Gson将其转换回一个JSon对象
如果你需要更详细的信息,请告诉我
更多说明:
假设您有两个不同的JSon字符串,称为JsonA和JSonB。
为了加入他们,你必须下载Gson库
class AClass{
int idA;
String nameA;
} // Note that the variable's names must be the same as the identifiers in JSON
class BClass{
int idB;
String nameB;
}
class JoinedClass{
BClass bClass;
AClass aClass; //don't forget getters and setters
}
public String joinJson(String JsonA , String JsonB){
Gson gson = new Gson();
AClass aClass = new AClass();
BClass bClass = new BClass();
aClass = gson.fromJson(JsonA, AClass.class);
bClass = gson.fromJson(JsonB, BClass.class);
JoinedClass joinedClass = new JoinedClass();
joinedClass.setAClass(aClass );
joinedClass.setBClass(bClass);
return gson.toJson(joinedClass);
}
// but you know, just after writing this code, i found that there might be an easier way to do this.
// Thanks for attention!
您的json无效。您最好先更改servlet端。您没有返回有效的json。您将两个JSON并排连接。是的,请详细说明您的答案…thnx