Java 将json应答从webservice传递给变量
我将一些数据发布到web服务,并得到一个json回复,我希望将其传递给jsonobject web服务的答复是:Java 将json应答从webservice传递给变量,java,android,json,arrays,jsonobject,Java,Android,Json,Arrays,Jsonobject,我将一些数据发布到web服务,并得到一个json回复,我希望将其传递给jsonobject web服务的答复是: { "ValidateLoginResult": [ { "ErrorMessage": "Wrong username pass", "PropertyName": null } ] } 我想把错误消息和属性名传递给变量。我尝试使用JSONobject和JSONarray,但没有任何运
{
"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");
您正在
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");