我是Android中的入门者。在我的项目中,我从HTTP响应中获得了以下json。从Json对象获取字符串值Android
[{"Date":"2012-1-4T00:00:00","keywords":null,"NeededString":"this is the sample string I am needed for my project","others":"not needed"}]
我想从上面的json中获取“NeededString”。如何获取它。
我是Android中的入门者。在我的项目中,我从HTTP响应中获得了以下json。从Json对象获取字符串值Android
[{"Date":"2012-1-4T00:00:00","keywords":null,"NeededString":"this is the sample string I am needed for my project","others":"not needed"}]
我想从上面的json中获取“NeededString”。如何获取它。
这可能会对您有所帮助。
JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String date = jObj.getString("NeededString");
谢谢你的快速回复。我知道了。非常感谢。 – Dray 2012-01-04 06:41:13
什么是服务器端的PHP代码发送响应? – 2014-06-29 12:26:50
这里是我的json格式,我得到json字符串,如下所示。但我想获得特定的价值,如何得到它? {“login”:[{“status”:“error”}]} – 2014-10-28 05:50:14
在您的项目中包含org.json.jsonobject
。
然后你可以这样做:
JSONObject jresponse = new JSONObject(responseString);
responseString = jresponse.getString("NeededString");
假设,responseString
持有收到的响应。
如果你需要知道如何为String接收到的响应转换,这里是如何做到这一点:
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
String responseString = out.toString();
感谢您的快速回复。 – Dray 2012-01-04 06:39:30
你只需要获得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();
}
感谢您的快速回复。 – Dray 2012-01-04 06:40:48
什么是服务器端的PHP代码发送响应? (使用该键“NeededString”) – 2014-06-29 12:37:44
如果你可以使用JSONObject库,你可以只
JSONArray ja = new JSONArray("[{\"Date\":\"2012-1-4T00:00:00\",\"keywords\":null,\"NeededString\":\"this is the sample string I am needed for my project\",\"others\":\"not needed\"}]");
String result = ja.getJSONObject(0).getString("NeededString");
感谢您的快速回复... – Dray 2012-01-04 06:39:58
我认为它有帮助到您
JSONArray jre = objJson.getJSONArray("Result");
for (int j = 0; j < your array NAme.length(); j++) {
JSONObject jobject = your array NAme.getJSONObject(j);
String date = jobject.getString("Date");
String keywords=jobject.getString("keywords");
String needed=jobject.getString("NeededString");
}
下面是我为我所用 的解决方案是为获取工程来自字符串的JSON
protected String getJSONFromString(String stringJSONArray) throws JSONException {
return new StringBuffer(
new JSONArray(stringJSONArray).getJSONObject(0).getString("cartype"))
.append(" ")
.append(
new JSONArray(employeeID).getJSONObject(0).getString("model"))
.toString();
}
您可以使用getString
String name = jsonObject.getString("name");
// it will throws exception if the key you specify doesn't exist
或optString
String name = jsonObject.optString("name");
// it will returns the empty string ("") if the key you specify doesn't exist
https://androidbeasts.wordpress.com/2015/08/04/json-parsing-tutorial/ – Aakash 2015-08-07 19:56:09