I have a Json response :
{
"action":"true",
"0":{
"_id":"58ca7f56e13823497175ee47"
}
}
and I want to show the _id value in a TextView
.
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
! 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
. 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
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. An array would be indicated by [ /* stuff here */ ]
, which you do not have.
You have a Json object containing action
and 0
, action
is a String, and 0
is an object.
In the 0
object you then have an _id
field which you are trying to access.
So in your case something like the following:
// get the object
JSONObject object0 = object.getJSONObject("0");
String message = object0.getString("_id");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.