从Json Object Android获取字符串值

Dra*_*ray 28 parsing android json

我是Android的初学者.在我的项目中,我从HTTP响应中获取以下json.

[{"Date":"2012-1-4T00:00:00",
"keywords":null,
"NeededString":"this is the sample string I am needed for my project",
"others":"not needed"}]
Run Code Online (Sandbox Code Playgroud)

我想从上面的json中获取"NeededString".怎么弄?

nis*_*3a5 65

这可能对你有帮助.

JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String date = jObj.getString("NeededString");
Run Code Online (Sandbox Code Playgroud)

  • 感谢你能这么快回复.我知道了.非常感谢. (2认同)

Lal*_*ani 10

你只需要使用循环来获取JSONArray和迭代JSONObject数组内部虽然在你的情况下只有一个JSONObject,但你可能有更多.

JSONArray mArray;
        try {
            mArray = new JSONArray(responseString);
             for (int i = 0; i < mArray.length(); i++) {
                    JSONObject mJsonObject = mArray.getJSONObject(i);
                    Log.d("OutPut", mJsonObject.getString("NeededString"));
                }
        } catch (JSONException e) {
            e.printStackTrace();
        }
Run Code Online (Sandbox Code Playgroud)


xbo*_*nez 6

包括org.json.jsonobject在您的项目中。

然后你可以这样做:

JSONObject jresponse = new JSONObject(responseString);
responseString = jresponse.getString("NeededString");
Run Code Online (Sandbox Code Playgroud)

假设,responseString持有您收到的响应。

如果您需要知道如何将接收到的响应转换为字符串,请按以下步骤操作:

ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();
Run Code Online (Sandbox Code Playgroud)


Pha*_*inh 6

您可以使用 getString

String name = jsonObject.getString("name");
// it will throws exception if the key you specify doesn't exist
Run Code Online (Sandbox Code Playgroud)

或者 optString

String name = jsonObject.optString("name");
// it will returns the empty string ("") if the key you specify doesn't exist
Run Code Online (Sandbox Code Playgroud)