【问题标题】:passing json reply from webservice to variables将 json 回复从 web 服务传递给变量
【发布时间】:2015-02-15 23:14:16
【问题描述】:

我正在向 Web 服务发布一些数据,并且我收到了一个我想要传递给 jsonobject 的 json 回复。

web服务的回复是:

{
    "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");

【问题讨论】:

  • 在这里展示你的努力。
  • How to parse JSON in Java的可能重复
  • 可能使用改造。它将为您完成大部分工作。

标签: java android json arrays jsonobject


【解决方案1】:

您在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");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-03-10
    • 1970-01-01
    • 2014-09-28
    • 2011-02-02
    • 2012-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多