转换JSON字符串JSON数组
你好,我叫一个服务,如果它包含多个对象,它使列表,但是当它仅包含一个对象时,它返回一个对象不是[]缺少一个列表,其实我想将它们转换成Java使用GSON但唯一例外的情况下,抛出异常,但是当它包含列表它做工精细其实我需要我的单身GSON字符串转换为数组类,请帮我..here是字符串转换JSON字符串JSON数组
{
"response":{
"projects":{
"project":{
"ixWorkflow":1,
"sEmail":"[email protected]",
"sPhone":"",
"ixProject":2,
"ixPersonOwner":2,
"fDeleted":false,
"sProject":"Project Default",
"fInbox":true,
"sPersonOwner":"junaid"
}
}
}
}
我想它就像
{
"response":{
"projects":{
"project":[
{
"ixWorkflow":1,
"sEmail":"[email protected]",
"sPhone":"",
"ixProject":6,
"ixPersonOwner":2,
"fDeleted":false,
"sProject":"project 2",
"fInbox":false,
"sPersonOwner":"junaid"
},
{
"ixWorkflow":1,
"sEmail":"[email protected]",
"sPhone":"",
"ixProject":2,
"ixPersonOwner":2,
"fDeleted":false,
"sProject":"Project Default",
"fInbox":true,
"sPersonOwner":"junaid"
}
]
}
}
}
参照t Øhttps://*.com/a/7284813/1105291
请尝试以下代码,您通过JSON来GSON的对象转换之前,并请让你得到任何错误我知道。只有我能看到的可能性是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
JSONObject [“project”]不是JSONArr它抛出这个异常 –
我用projectsJsonObject.optJSONArray(“project”)而不是projectsJsonObject.getJSONArray(“project”)== null反正休息很好,非常感谢很多 –
@JunaidAkhtar I was期待异常但在其他地方,但我很高兴它帮助:) –
JsonParser parser = new JsonParser();
JsonObject o = (JsonObject)parser.parse("{\"a\": \"A\"}");
请添加更多的 '句号' 你的问题。这看起来更像是读一本弗吉尼亚伍尔夫小说。 – aquaraga
请包括您尝试过的代码。 – 2013-12-11 11:55:54
你可以请包括你的解析代码。 –