我正在向Web服务发布一些数据,我收到了一个json回复,我希望将其传递给jsonobject。
网络服务的回复是:
{
"ValidateLoginResult": [
{
"ErrorMessage": "Wrong username pass",
"PropertyName": null
}
]
}
我希望将错误消息和属性名称传递给变量。我尝试过使用JSONobject和JSONarray,但没有运气
HttpClient httpclient = new DefaultHttpClient();
// 2. make POST request to the given URL
HttpPost httpPost = new HttpPost(serverURL);
StringEntity se = new StringEntity(data);
httpPost.setEntity(se);
// 7. Set some headers to inform server about the type of the content
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
// 8. Execute POST request to the given URL
HttpResponse httpResponse = httpclient.execute(httpPost);
// 9. Getting Reply
inputStream = httpResponse.getEntity().getContent();
...
...
JSONArray json = new JSONArray(convertInputStreamToString(inputStream));
JSONObject json_LL = json.getJSONObject(0);
String str_value=json_LL.getString("ErrorMessage");
答案 0 :(得分:0)
您正在JSONObject
收到回复,并且您正试图在JSONArray
中收到回复..这就是您收到错误的原因..
试试这种方式......
try {
JSONObject result = new JSONObject(response);
if(data.has("ValidateLoginResult"){
JSONArray array = result.getJSONArray("ValidateLoginResult");
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(i);
String ErrorMessage= ""+obj.getString("ErrorMessage");
String PropertyName= ""+obj.getString("PropertyName");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
或
如果你想要一行答案..试试这个..
// going directly to array object..
JSONObject result = new JSONObject(response).getJSONArray("ValidateLoginResult").getJSONObject(0);
String ErrorMessage= ""+result.getString("ErrorMessage");
String PropertyName= ""+result.getString("PropertyName");