[英]Convert JSON String to JSON Array
Hello i call a service if it contains multiple objects it make list but when it contain only one object it return a single object not a list [] are missing , actually i want to convert them into java class using gson but in case of single exception it throw exception but when it contain list it work fine i actually need to convert my single gSON string to array ,please help me ..here is the string 您好,我致电服务,如果它包含多个对象,则列出该列表,但是当它仅包含一个对象时,它返回一个对象,而不是列表[]丢失,实际上我想使用gson将它们转换为java类,但是在单个异常的情况下它抛出异常,但是当它包含列表时,它工作正常,我实际上需要将我的单个gSON字符串转换为数组,请帮助我..这是字符串
{
"response":{
"projects":{
"project":{
"ixWorkflow":1,
"sEmail":"j.a@loxvo.com",
"sPhone":"",
"ixProject":2,
"ixPersonOwner":2,
"fDeleted":false,
"sProject":"Project Default",
"fInbox":true,
"sPersonOwner":"junaid"
}
}
}
}
i want it to be like same as 我希望它像
{
"response":{
"projects":{
"project":[
{
"ixWorkflow":1,
"sEmail":"j.a@loxvo.com",
"sPhone":"",
"ixProject":6,
"ixPersonOwner":2,
"fDeleted":false,
"sProject":"project 2",
"fInbox":false,
"sPersonOwner":"junaid"
},
{
"ixWorkflow":1,
"sEmail":"j.a@loxvo.com",
"sPhone":"",
"ixProject":2,
"ixPersonOwner":2,
"fDeleted":false,
"sProject":"Project Default",
"fInbox":true,
"sPersonOwner":"junaid"
}
]
}
}
}
With reference to https://stackoverflow.com/a/7284813/1105291 参考https://stackoverflow.com/a/7284813/1105291
Please try below code before you pass json to Gson for object conversion, and please let me know if you get any error. 在将json传递给Gson进行对象转换之前,请尝试以下代码,如果出现任何错误,请告诉我。 Only posibility that I can see is exception at if. 我只能看到的可能性是if的例外。
JSONObject jsonObject = new JSONObject(responseString);
JSONObject projectsJsonObject = jsonObject.getJSONObject("response").getJSONObject("projects");
if(projectsJsonObject.getJSONArray("project") == null)
{
JSONArray jsonArray = new JSONArray();
jsonArray.put(projectsJsonObject.getJSONObject("project"));
projectsJsonObject.put("project", jsonArray);
}
//Pass jsonObject to Gson
Use Google Gson 使用Google Gson
JsonParser parser = new JsonParser();
JsonObject o = (JsonObject)parser.parse("{\"a\": \"A\"}");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.