[英]Showing json response in TextView
I have a Json response : 我有一个Json回应:
{
"action":"true",
"0":{
"_id":"58ca7f56e13823497175ee47"
}
}
and I want to show the _id value in a TextView
. 我想在
TextView
显示_id值。
I tried this : 我尝试了这个:
StringRequest stringRequest = new StringRequest(Request.Method.POST, reg_url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
JSONArray Jarray = object.getJSONArray("0");
String message = object.getString("_id");
txtstorename.setText(message);
I can see Json response in Android Monitor but I got nothing in my TextView
! 我可以在Android Monitor中看到Json的响应,但
TextView
什么也没有! what is the problem? 问题是什么?
This will be the correct way 这是正确的方法
JSONObject object = new JSONObject(response);
JSONObject object1 = object.get("0");
String message = object1.get("_id");
txtstorename.setText(message);
StringRequest stringRequest = new StringRequest(Request.Method.POST, reg_url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject object = new JSONObject(response);
JSONObject jsonObj= object.getJSONObject("0");
String message = jsonObj.getString("_id");
txtstorename.setText(message);
You are getting JsonObject
into JsonArray
. 您正在将
JsonObject
放入JsonArray
。 thats why there is problem. 那就是为什么有问题。
replace this line: 替换此行:
JSONArray Jarray = object.getJSONArray("0");
with This 有了这个
JsonObject jsonObject = object.getJSONObject("0");
When receiving JSON Object as response use JsonObjectRequest instead of StringRequest 接收JSON对象作为响应时,请使用JsonObjectRequest而不是StringRequest
JsonObjectRequest request= new JsonObjectRequest(Request.Method.POST,url, null,new Response.Listener<JSONObject>(){@Override
public void onResponse(JSONObject response) {
try {
JSONObject jsonObj= response.getJSONObject("0");
String message = jsonObj.getString("_id");
txtstorename.setText(message);},null);
You have to use getJSONObject("0")
instead of getJSONArray
because 0
is not an array. 您必须使用
getJSONObject("0")
而不是getJSONArray
因为0
不是数组。 An array would be indicated by [ /* stuff here */ ]
, which you do not have. 数组将由
[ /* stuff here */ ]
,而您没有。
You have a Json object containing action
and 0
, action
is a String, and 0
is an object. 您有一个Json对象,其中包含
action
和0
, action
是一个String,而0
是一个对象。
In the 0
object you then have an _id
field which you are trying to access. 然后,在
0
对象中,您有一个_id
字段要尝试访问。
So in your case something like the following: 因此,在您的情况下,如下所示:
// get the object
JSONObject object0 = object.getJSONObject("0");
String message = object0.getString("_id");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.