Ошибка jsonexception no value for type вконтакте

I know that there are several questions posted on here with the same topic and error, but none of them indicate the same problem as mine, so I decided to post my question here, hoping that someone would help me point out the cause.
So I’m trying to implement the login feature in my app and here’s the code:

if (tag.equalsIgnoreCase(login_tag)){
                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        String res = json.getString(KEY_SUCCESS);
                        if(Integer.parseInt(res) == 1){
                            // user successfully logged in
                            // Store user details in SQLite Database
                            DatabaseHandler db = new DatabaseHandler(mContext);
                            JSONObject json_user = json.getJSONObject("user");

                            // Clear all previous data in database
                            logoutUser(mContext);
                            Toast.makeText(mContext, json.toString(3), Toast.LENGTH_LONG).show();
                            db.addUser(json_user.getString(KEY_EMAIL), json_user.getString(KEY_NAME), json.getString(KEY_UID), json.getString(KEY_AVA), json_user.getString(KEY_BDAY), json_user.getString(KEY_COUNTRY), json_user.getString(KEY_PREF), json_user.getString(KEY_SPEND));  

                            // Launch Dashboard Screen
                            Intent dashboard = new Intent(mContext, DashboardActivity.class);

                            // Close all views before launching Dashboard
                            dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            mContext.startActivity(dashboard);

                            // Close Login Screen
                            ((Activity) mContext).finish();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

And this is the JSON response I got when logging in:

{
    "tag": "login",
    "success": 1,
    "error": 0,
    "uid": "5123",
    "user": {
        "email": "abcxyz@gmail.com",
        "name": "abc",
        "avatar": "avatars/img_hzsxda_2013-03-18-11-03-33.jpg",
        "bday": "1991-02-01",
        "country": "Australia",
        "preferences": "none",
        "spending": "none"
    }
}

So apparently there is a value for avatar, but I still got this warning in my logcat:

03-18 12:06:36.972: W/System.err(24574): org.json.JSONException: No value for avatar

Since no value avatar is got, I can’t complete addUser, hence login fails.
Please help me find the error and how to solve it. Thank you.

у меня проблема с кодом синтаксического анализа json, он показывает ошибку json, нет значения для konteks lokasi, которая использует переменную TAG_KONTEKS. Это мой код для получения ответа json.

@Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        //mendapatkan data dari database berupa alamat, konteks, latitude, longitude
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("lat", Integer.toString(latPengguna)));
        params.add(new BasicNameValuePair("lng", Integer.toString(lngPengguna)));
        params.add(new BasicNameValuePair("konteks", konteksCocok));
        Log.d("lat dan lng kirim", "data: " + Integer.toString(latPengguna) + " " + Integer.toString(lngPengguna));
        Log.d("konteks kirim", "data: " + konteksCocok);
        JSONObject json = jParser.makeHttpRequest(url_webservice, "POST", params);
        Log.d("data: ", json.toString());

        //menampilkan data lokasi POI
        try {
            int sukses = json.getInt(TAG_SUCCESS);
            if(sukses == 1) {
                POI = json.getJSONArray(TAG_POIN);
                for(int i = 0; i < POI.length(); i++) {
                    JSONObject c = POI.getJSONObject(i);
                    int latDB = c.getInt(TAG_LAT);
                    int lngDB = c.getInt(TAG_LNG);
                    String alamat = c.getString(TAG_ALAMAT);
                    String konteks = c.getString(TAG_KONTEKS);

                    Log.d("latDB", "data: " + latDB);
                    Log.d("lngDB", "data: " + lngDB);
                    Log.d("altDB", "data: " + alamat);
                    Log.d("ktsDB", "data: " + konteks);                     
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put(TAG_ALAMAT, alamat);
                    map.put(TAG_KONTEKS, konteks);
                    POIList.add(map);
                }
            } else {
                Log.d("JSON error", "JSON trouble");
            }
        } catch(JSONException ex) {
            ex.printStackTrace();
        }
        return null;
    }

Это мой ответ json:

{
"success": 1,
"point": [
    {
        "point": {
            "konteks_lokasi": "kuliah",
            "nama_lokasi": "Teknik Perkapalan",
            "longitude": "-60",
            "latitude": "117"
        },
        "hasil": 15.811388300842
    },
    {
        "point": {
            "konteks_lokasi": "kuliah",
            "nama_lokasi": "Teknik Kimia",
            "longitude": "-80",
            "latitude": "145"
        },
        "hasil": 33.376638536557
    },
    {
        "point": {
            "konteks_lokasi": "kuliah",
            "nama_lokasi": "Teknik Arsitektur",
            "longitude": "-22",
            "latitude": "111"
        },
        "hasil": 53.009433122794
    }
]

}

Я был бы очень рад, если бы вы могли мне помочь…

После небольшой корректировки ответа JSON ошибка изменилась на W/System.err: org.json.JSONException: No value for retCode.

Полная ошибка:

04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: org.json.JSONException: No value for retCode
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.ActivityRegister$2.serviceResult(ActivityRegister.java:194)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.Net$1$1.run(Net.java:420)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Looper.loop(Looper.java:148)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-03 12:53:26.703 14366-14454/com.allianz.azemployee V/RenderScript: 0x9d789000 Launching thread(s), CPUs 4

Это мой класс ActivityRegister.java:

public class ActivityRegister extends AppCompatActivity implements View.OnClickListener {

    Button btnRequestPin, btnConfirm, btnRequestNewPin;
    EditText editTextEmail;
    EditText editTextPin;

    private static final String FIRST_START_KEY = "first_start";
    private static final boolean ALWAYS_SEND_FIRST_START_BROADCAST = false;

    private String emailTemp, tokenTemp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        btnRequestPin = (Button)findViewById(R.id.btn_request_pin);
        btnConfirm = (Button)findViewById(R.id.btn_confirm);
        btnRequestNewPin = (Button)findViewById(R.id.btn_request_newpin);
        editTextEmail = (EditText) findViewById(R.id.editText_mail);
        editTextPin = (EditText) findViewById(R.id.editText_pin);

        btnRequestPin.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        btnRequestNewPin.setOnClickListener(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        Intent intent = new Intent(this,ActivityLogin.class);
        this.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if(v == btnConfirm){

            final String email = editTextEmail.getText().toString();
            final String token = editTextPin.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            if (token == null || token.length() == 0){
                Toast.makeText(this,"OTP required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            String postBody = Net.getInstance().getJSONForRegister(email,token);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){

                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.nn"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if (retCodeInt==0) { //Registration success

                                //Store user-email and token
                                Net.getInstance().saveUserWithValues(ActivityRegister.this, email, token, "");
                                //Take user to login screen.
                                ActivityRegister.this.finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for registration. Try again.");
                        }
                    }
                }
            });
        }
        if(v == btnRequestPin || v == btnRequestNewPin){

            final String email = editTextEmail.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            final Button button = (Button) v;
            String postBody = Net.getInstance().getJSONForPinGeneration(email);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){
                        Log.i("Aditi","errorMsg== " +errorMsg);
                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.nn"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            Log.i("Aditi","retCode===" + retCode + " ,status== "+status);
                            Log.i("Aditi","errorMsg== " +errorMsg);

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if(retCodeInt == 0 && button == btnRequestNewPin){

                                ActivityRegister.this.finish(); //take user to login on success.
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for pin generation. Try again.");
                        }
                    }

                }
            });
        }
    }
}

Это строка ответа, которую я даю:

public void callServiceWithURLPart(final Activity activity, final String urlPart, final String postBody, final ICallServiceResult callServiceResult){

        final ProgressDialog progress = new ProgressDialog(activity);
        progress.setTitle("Processing..");
        progress.setProgressStyle(android.R.attr.progressBarStyleSmall);
        //progress.setMessage("Connecting...");
        progress.show();

        ConnectivityManager connMgr = (ConnectivityManager)
                activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {


            Runnable r = new Runnable() {
                @Override
                public void run() {

                    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).build();

                    try{

                        String servicePath = kURLBase + urlPart;

                        Log.d("OkHttpClient","servicePath = "+servicePath);
                        Log.d("postBody",postBody);

                        Request request = new Request.Builder()
                                .url(servicePath)
                                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody))
                                .build();

                        final Response response = client.newCall(request).execute();
                        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                        //final String stringResponse = response.body().string();

                        final String stringResponse = "{'serviceName': 'registerToken', 'emailID': '', 'token': ''}";

                        if(stringResponse!=null){
                            Log.d("ServiceResponseString",stringResponse);
                        }else {
                            Log.d("ServiceResponseString","null");
                        }

                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
                                    if(stringResponse!=null){
                                        callServiceResult.serviceResult(urlPart,true,stringResponse);
                                    }
                                    else {
                                        callServiceResult.serviceResult(urlPart,false,stringResponse);
                                    }
                                }
                            });
                        }
                    } catch (Exception e){

                        Log.d("OkHttpClient exception",e.toString());
                        final Exception _e = e;
                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
           callServiceResult.serviceResult(urlPart,false,_e.toString());
                                }
                            });
                        }
                    }
                }
            };
            Thread t = new Thread(r);
            t.start();
        } else {
            progress.dismiss();
            fastToast(activity,"Connect to internet and try again.");
        }
    }

Мой базовый URL: public static final String kURLBase = "https://api-test.allianz.com/digithonempwebservice/rest";, который предоставляется при запросе stringResponse. Любая помощь будет оценена.

У меня есть RESTful API, работающий на моем локальном компьютере, который возвращает ответ в формате JSON (на самом деле этот JSON является ответом на запрос клиента Nodejs Soap) в зависимости от запроса. В этом конкретном случае я получаю запрос POST от клиента Android и возвращаю следующий ответ:

{
    QueryAcctBalResponse: {
        BalExDtoList: {
            BalExDto: [{
                BalID: "xxxx",
                AcctResID: "xxxx",
                AcctResName: "xxxx",
                BalType: "xxxx",
                Balance: "xxxx",
                EffDate: "xxxx",
                ExpDate: "xxxx",
                UpdateDate: "xxxx"
            }, {
                BalID: "yyyy",
                AcctResID: "yyyy",
                AcctResName: "yyyy",
                BalType: "yyyy",
                Balance: "yyyy",
                EffDate: "yyyy",
                ExpDate: "yyyy",
                UpdateDate: "yyyy"
            }]
        }
    }
}

Проблема заключается в том, что каждый раз, когда я пытаюсь проанализировать этот ответ и отобразить эту информацию в Android (в частности, «AcctResName»). Я получаю org.json.JSONException: нет значения для BalExDto. Я использую Volley Libray в Android для анализа Json, и я использовал запрос Jsonobject.

Код заявки.

JsonObjectRequest sq = new JsonObjectRequest(Request.Method.POST, balanceUrl, request, new Response.Listener<JSONObject>() {

    @Override
    public void onResponse(JSONObject response) {

        try {
            JSONArray jsonArray = response.getJSONArray("BalExDto");
            for (int i = 0; i < jsonArray.length(); i++){
                JSONObject jsonObject=jsonArray.getJSONObject(i);
                Toast.makeText(CheckBalance.this, ""+jsonObject.get("AcctResName"), Toast.LENGTH_LONG).show();
            }

            pd.hide();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        Log.d("Response", "Response_TAG: "+response);

    }

Перейти к ответу
Данный вопрос помечен как решенный


Ответы
3

BalExDto массив не является прямым дочерним элементом ответа. Он находится внутри BalExDtoList, который находится внутри QueryAcctBalResponseобъекта. Вы не можете напрямую получить доступ к любому узлу в JSON, вам нужно пройти полный путь, прежде чем вы сможете получить к ним доступ.

Вам нужно получить массив, как показано ниже

JSONObject queryAcctBalResponse = response.getJSONObject("QueryAcctBalResponse");
JSONObject balExDtoList = queryAcctBalResponse.getJSONObject("BalExDtoList");
JSONArray jsonArray = balExDtoList.getJSONArray("BalExDto");

Это потому, что у вас нет массива JSON, у вас есть объект JSON.

Прежде всего, вам нужно получить объект JSON из вашего ответа API,

JSONObject jsonObject = response.getJSONObject("QueryAcctBalResponse")

И внутри этого объекта JSON находится массив JSON.

JSONArray jsonArray = response.getJSONArray("BalExDtoList");

Ошибка говорит — вы парсите BalExDto неправильно. BalExDto не является прямым потомком response. Итак, вам нужно разобрать QueryAcctBalResponse и BalExDtoList, и тогда вы сможете получить BalExDto. Потому что BalExDto внутри BalExDtoList и BalExDtoList внутри QueryAcctBalResponse.

JsonObjectRequest sq = new JsonObjectRequest(Request.Method.POST, balanceUrl, request, new Response.Listener<JSONObject>() {

@Override
public void onResponse(JSONObject response) {

    try {
        JSONObject queryAcctBalResponse = response.getJSONObject("QueryAcctBalResponse");
        JSONObject balExDtoList = queryAcctBalResponse.getJSONObject("BalExDtoList");
        JSONArray jsonArray = balExDtoList.getJSONArray("BalExDto");
        for (int i = 0; i < jsonArray.length(); i++){
            JSONObject jsonObject=jsonArray.getJSONObject(i);
            Toast.makeText(CheckBalance.this, ""+jsonObject.get("AcctResName"), Toast.LENGTH_LONG).show();
        }

        pd.hide();
    } catch (JSONException e) {
        e.printStackTrace();
    }
    Log.d("Response", "Response_TAG: "+response);

}

Другие вопросы по теме

During the execution of the application I received a JSONException error No Value for

{
"time": "05:07:18 AM",
"milliseconds_since_epoch": 1504588038515,
"date": "09-05-2017"
}

I know there are a lot of errors reported, but everyone I read did not get a result. Follow the codes.

Main Activity:

package com.example.joo.myapplication;

import android.app.ProgressDialog;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class MainActivity extends AppCompatActivity {
private static final String URL_DATA = "http://date.jsontest.com";
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private List<ListItem> listItems;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));

listItems = new ArrayList&lt;&gt;();
loadRecyclerViewData();

}

private void loadRecyclerViewData(){

StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_DATA, new Response.Listener&lt;String&gt;() {
    @Override
    public void onResponse(String response) {
        try{
            JSONObject jsonObject = new JSONObject(response);
            JSONArray array = jsonObject.getJSONArray(response);

                JSONObject o = array.getJSONObject(0);
                ListItem item = new ListItem(
                  o.optString("time"),
                        o.optString("milliseconds_since_epoch"),
                        o.optString("date")
                );
                listItems.add(item);


            adapter = new MyAdapter(getApplicationContext(),listItems);
            recyclerView.setAdapter(adapter);

        }catch (JSONException e){
            e.printStackTrace();
            Toast.makeText(MainActivity.this, e.toString(),Toast.LENGTH_LONG).show();
        }
    }
},
new Response.ErrorListener(){
    @Override
    public void onErrorResponse(VolleyError volleyError){
        Toast.makeText(MainActivity.this, volleyError.toString(),Toast.LENGTH_LONG).show();
    }
});

RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);

}

}

List Item:

package com.example.joo.myapplication;

public class ListItem {
public String time, milliseconds_since_epoch, date;

public ListItem(String time, String milliseconds_since_epoch, String date) {
this.time = time;
this.milliseconds_since_epoch = milliseconds_since_epoch;
this.date = date;
}

public String getTime() {
return time;
}

public void setTime(String time) {
this.time = time;
}

public String getMilliseconds_since_epoch() {
return milliseconds_since_epoch;
}

public void setMilliseconds_since_epoch(String milliseconds_since_epoch) {
this.milliseconds_since_epoch = milliseconds_since_epoch;
}

public String getDate() {
return date;
}

public void setDate(String date) {
this.date = date;
}
}

My Adapter:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder>{
private Context context;
private List<ListItem> items;

public MyAdapter(Context context, List<ListItem> items) {
this.context = context;
this.items = items;
}

@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item,parent,false);
return new ViewHolder(v);
}

@Override
public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
holder.date.setText(items.get(position).getTime());
holder.time.setText(items.get(position).getMilliseconds_since_epoch());
holder.mili.setText(items.get(position).getDate());
}

@Override
public int getItemCount() {
return items.size();
}

public class ViewHolder extends RecyclerView.ViewHolder{
public TextView date, time, mili;

public ViewHolder(View itemView) {
    super(itemView);
    date = (TextView) itemView.findViewById(R.id.ViewDesc);
    time = (TextView) itemView.findViewById(R.id.ViewHead);
    mili = (TextView) itemView.findViewById(R.id.ViewImg);

}
}
}

I want to display my friend’s list.I don’t understand why String cannot converted to json. I understand that error in 152(MainActivity)

JSONObject o = new JSONObject(response.toString());

but i don’t know why…

JSONException: Value com.vk.sdk.api.VKResponse@42b49418 of type java.lang.String cannot be converted to JSONObject

In logs this response show Response:

 {
    "response": {
        "count": 40,
        "items": [{
                    "id": 10543136,
                    "first_name": "Филип",
                    "last_name": "Канна",
                    "sex": 2,
                    "city": {
                        "id": 1710959,
                        "title": "Кишинев"
                    },
                    "online": 0
                }, ........

How JSON looks like VK server

response: {
    count: 693,
    items: [{
        id: 1987761,
        first_name: 'Александром',
        last_name: 'Мирмильштейном',
        sex: 2,
        city: {
            id: 60,
            title: 'Казань'
        },
        online: 0
    }, {
        id: 153796,
        first_name: 'Александром',
        last_name: 'Москалюком',
        sex: 2,
        city: {
            id: 1568,
            title: 'Черновцы'
        },
        online: 0
    }, {
        id: 10741,
        first_name: 'Александром',
        last_name: 'Мынзой',
        sex: 2,
        city: {
            id: 1,
            title: 'Москва'
        },
        online: 0
    }]
 }

My MainActivity

public class MainActivity extends Activity {
TextView text;
getFriendTask task;
ListView listView1;
VKAccessToken token;


ArrayList<Friend> friendArrayList;
ArrayAdapter<Friend> adapter;




@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    VKUIHelper.onCreate(this);
    VKSdk.initialize(listener, "4571964");
    VKSdk.authorize(new String[]{"friends"});



    text=(TextView)findViewById(R.id.txt);
}



public void FriendClick(View view) {

     friendArrayList=new ArrayList<Friend>();
               task=new getFriendTask();
                task.execute();
                listView1=(ListView)findViewById(R.id.list);
                adapter=new FriendAdapter(getApplicationContext(), R.layout.friendlist, friendArrayList);
                listView1.setAdapter(adapter);



}

class getFriendTask extends AsyncTask<Void, Void, Void> {


    protected void onPostExecute(Void result){
        super.onPostExecute(result);
        adapter.notifyDataSetChanged();
    }


    @Override
    protected Void doInBackground(Void... params) {
        if(listener!=null) {
            VKRequest request = new VKRequest("friends.get", VKParameters.from(VKApiConst.FIELDS, "first_name, last_name, sex, bdate, city"));
            request.start();

            request.executeWithListener(new VKRequest.VKRequestListener() {

                                            @Override
                                            public void onComplete(VKResponse response) {
                                                super.onComplete(response);
                                                Toast.makeText(MainActivity.this, response.responseString, Toast.LENGTH_LONG).show();
            try{

                    JSONObject o = new JSONObject(response.toString());
                    JSONArray jsonArray = o.getJSONArray("response");

                    for (int i = 0; i < jsonArray.length(); i++) {
                        JSONObject jsonObject = jsonArray.getJSONObject(i);
                        Friend fr = new Friend();

                        fr.setFirst_name(jsonObject.getString("first_name"));
                        fr.setLast_name(jsonObject.getString("last_name"));
                        fr.setSex(jsonObject.getString("sex"));
                        fr.setBdate(jsonObject.getString("bdate"));
                        fr.setCity(jsonObject.getString("city"));

                        friendArrayList.add(fr);



                }

            }catch (JSONException e){
                e.printStackTrace();
            }
                Log.i("Are You Ready???", "Response - "+response.responseString);

                                            }

                @Override
                public void onError(VKError error) {
                    super.onError(error);
                    Log.i("Are You Ready to Fly???", "EEEror - "+error.errorMessage);

                }

                @Override
                public void attemptFailed(VKRequest request, int attemptNumber, int totalAttempts) {
                    super.attemptFailed(request, attemptNumber, totalAttempts);

                }
            });
        }
        return null;
    }


}






VKSdkListener listener=new VKSdkListener() {
    @Override
    public void onCaptchaError(VKError vkError) {


    }

    @Override
    public void onTokenExpired(VKAccessToken vkAccessToken) {

    }

    @Override
    public void onAccessDenied(VKError vkError) {
        Log.d("Gooooo", " My error - "+vkError.errorMessage);
    }
    public void onReceiveNewToken(VKAccessToken newToken){

        Log.d("Gooooo", "My token - "+newToken.accessToken);

        token=newToken;

    }

};

@Override
protected void onResume() {
    super.onResume();
    VKUIHelper.onResume(this);
}

@Override
protected void onDestroy() {
    super.onDestroy();
    VKUIHelper.onDestroy(this);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    VKUIHelper.onActivityResult(requestCode, resultCode, data);
}

public void onAutoClick(View view) {
}}

My Model Friend

  class Friend{

    String first_name;
    String last_name;
    String sex;
    String bdate;
    String city;         
        public Friend(){}
      public Friend(String first_name, String last_name, String sex, String bdate, String city){
    super();
    this.first_name=first_name;
    this.last_name=last_name;
    this.sex=sex;
    this.bdate=bdate;
    this.city=city;
    }

     public String getFirst_name(){
    return first_name;
    }
     public void setFirst_name(String first_name){
    this.first_name=first_name;
    }
     public String getLast_name(){
    return last_name;
    }
     public void setLast_name(String last_name){
    this.last_name=last_name;
    }
     public String getSex(){
    return sex;
    }
     public void setSex(String sex){
    this.sex=sex;
    }
     public String getBdate(){
    return bdate;
    }
     public void setBdate(String bdate){
    this.bdate=bdate;
    }
     public String getCity(){
    return city;
    }
     public void setCity(String city){
    this.city=city;
    }
    }

My FriendAdapter

      public class FriendAdapter extends ArrayAdapter<Friend> {
 ArrayList<Friend> friendArrayList;
LayoutInflater inflater;
int Resource;
ViewHolder holder = new ViewHolder();

public FriendAdapter(Context context, int resource, ArrayList<Friend> objects) {
    super(context, resource, objects);
    inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    Resource=resource;
    friendArrayList=objects;
}

@Override
public View getView(int position, View convertView, ViewGroup parent){
    View view=convertView;

    if(view==null){
    holder=new ViewHolder();
        view=inflater.inflate(Resource, null);
        holder.name=(TextView)view.findViewById(R.id.fname);
        holder.laname=(TextView)view.findViewById(R.id.lname);
        holder.s=(TextView)view.findViewById(R.id.sx);
        holder.b=(TextView)view.findViewById(R.id.bd);
        holder.c=(TextView)view.findViewById(R.id.ct);
        view.setTag(holder);
    }else{
        holder=(ViewHolder) view.getTag();
    }
    holder.name.setText(friendArrayList.get(position).getFirst_name());
    holder.laname.setText(friendArrayList.get(position).getLast_name());
    holder.s.setText(friendArrayList.get(position).getSex());
    holder.b.setText(friendArrayList.get(position).getBdate());
    holder.c.setText(friendArrayList.get(position).getCity());
    return view;
}
static class ViewHolder {
    public TextView name;
    public TextView laname;
    public TextView s;
    public TextView b;
    public TextView c;
} }

Error

10-25 22:57:33.130  31812-31812/standandroid.ru.vktestapi W/System.err﹕ org.json.JSONException: Value com.vk.sdk.api.VKResponse@42b40ac0 of type java.lang.String cannot be converted to JSONObject
10-25 22:57:33.130  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at org.json.JSON.typeMismatch(JSON.java:111)
10-25 22:57:33.130  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:158)
10-25 22:57:33.130  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at org.json.JSONObject.<init>(JSONObject.java:171)
10-25 22:57:33.140  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at standandroid.ru.vktestapi.MainActivity$getFriendTask$1.onComplete(MainActivity.java:152)
10-25 22:57:33.140  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at com.vk.sdk.api.VKRequest$3.run(VKRequest.java:459)
10-25 22:57:33.150  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at android.os.Handler.handleCallback(Handler.java:730)
10-25 22:57:33.150  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:92)
10-25 22:57:33.150  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
10-25 22:57:33.150  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:5137)
10-25 22:57:33.150  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
10-25 22:57:33.150  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:525)
10-25 22:57:33.150  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:756)
10-25 22:57:33.150  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:572)
10-25 22:57:33.150  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at miui.dexspy.DexspyInstaller.main(DexspyInstaller.java:171)
10-25 22:57:33.160  31812-31812/standandroid.ru.vktestapi W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
10-25 22:57:33.160  31812-31812/standandroid.ru.vktestapi I/Are You Ready???﹕ Response - {"response":{"count":40,"items":[{"id":10543136,"first_name":"Филип","last_name":"Канна","sex":2,"city":{"id":1710959,"title":"Кишинев"},"online":0},{"id":12567913,"first_name":"Юлия","last_name":"Мурашева","sex":1,"bdate":"4.4","city":{"id":1710959,"title":"Кишинев"},"online":1},{"id":15349233,"first_name":"Алёна","last_name":"Волкова","sex":1,"bdate":"31.3","city":{"id":1710959,"title":"Кишинев"},"online":1},{"id":15890365,"first_name":"Алиса","last_name":"Голдур","sex":1,"bdate":"25.2","city":{"id":1710959,"title":"Кишинев"},"online":0},{"id":17445476,"first_name":"Лена","last_name":"Стурза","sex":1,"bdate":"6.3.1995","online":1},{"id":20855237,"first_name":"Никита","last_name":"Чукля","sex":2,"online":1},{"id":22441902,"first_name":"Максим","last_name":"Чакир","sex":2,"bdate":"4.1.1994","city":{"id":1710959,"title":"Кишинев"},"online":1},{"id":23260033,"first_name":"Катя","last_name":"Кузьмина","sex":1,"bdate":"27.6.1994","city":{"id":1710959,"title":"Кишинев"},"online":0},{"id":24891252,"first_name":"Арина","last_name":"Горобец","sex":1,"bdate":"20.12.1994","city":{"id":1710959,"title":"Кишинев"},"online":1},{"id":33387222,"first_name":"Алёна","last_name":"Миколюк","sex":1,"bdate":"14.10","city":{"id":292,"title":"Одесса"},"online":1},{"id":38467274,"first_name":"Андрей","last_name":"Тросиненко","sex":2,"bdate":"19.3","online":0},{"id":38733273,"first_name":"Миха","last_name":"Романчук","sex":1,"bdate":"2.6.1937","city":{"id":1710959,"title":"Кишинев"},"online":0},{"id":39117080,"first_name":"Рома","last_name":"Беженарь","sex":2,"bdate":"14.10","city":{"id":1710959,"title":"Кишинев"},"online":1},{"id":45171519,"first_name":"Александр","last_name":"Огурцов","sex":2,"bdate":"22.6.1994","city":{"id":1710959,"title":"Кишинев"},"online":0},{"id":47147705,"first_name":"Никита","last_name":"Драгуцану","sex":2,"bdate":"28.12","city":{"id":1710959,"title":"Кишинев"},"online":0},{"id":58606740,"first_name":"Франческа","last_name":"Канна","sex":1,"bdate":"25.1","city":{"id":1710959,"title":"Кишинев"},"online":0},{"id":62678153,"first_name":"Лёша","last_name":"Кугут","sex":2,"city":{"id":1710959,"title":"Кишинев"},"online":0},{"id":67485434,"first_name":"Ирина","last_name":"Трапезникова","sex":1,"bdate":"15.7","city":{"id":1710959,"title":"Кишинев"},"online":1},{"id":76249958,"first_name":"Никита","last_name":"Литвинов","sex":2,"online":1},{"id":78574119,"first_name":"Женя","last_name":"Чередниченко","sex":2,"city":{"id":1710959,"title":"Кишинев"},"online":0},{"id":87816032,"first_name":"Саша","last_name":"Сергунин","sex":2,"bdate":"28.5.1994","city":{"id":1710959,"title":"Кишинев"},"online":0},{"id":91235673,"first_name":"Вадим","last_name":"Барский","sex":2,"bdate":"22.6.1994","city":{"id":1908479,"title":"Antananarivo"},"online":1},{"id":94373404,"first_name":"Никита","last_name":"Головко","sex":2,"bdate":"29.1","city":{"id":1710959,"title":"Кишинев"},"online":1},{"id":101047911,"first_name":"Алексей","last_name":"Кицак","sex":2,"bdate":"12.5","city":{"id":1710959,"title":"Кишинев"},"online":1},{"id":101208573,"first_name":"Глеб","last_name":"Глинянов","deactivated":"deleted","sex":2,"online":0},{"id":108330289,"first_name":"Саша","last_name":"Руденко","sex":2,"bdate":"16.6","online":0},{"id":129188949,"first_name":"Роман","last_name":"Бугаян","sex":2,"city":{"id":1710959,"title":"Кишинев"},"online":0},{"id":139584680,"first_name":"Кристиан","last_name":"Мбала","sex":2,"bdate":"10.6","city":{"id":1710959,"title":"Кишинев"},"online":0},{"id":154083054,"first_name":"Оля","last_name":"За

После небольшой корректировки ответа JSON ошибка изменилась на W/System.err: org.json.JSONException: No value for retCode.

Полная ошибка:

04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err: org.json.JSONException: No value for retCode
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.get(JSONObject.java:389)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at org.json.JSONObject.getString(JSONObject.java:550)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.ActivityRegister$2.serviceResult(ActivityRegister.java:194)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at com.allianz.azemployee.Net$1$1.run(Net.java:420)
04-03 12:53:26.624 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.handleCallback(Handler.java:739)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Handler.dispatchMessage(Handler.java:95)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.os.Looper.loop(Looper.java:148)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at android.app.ActivityThread.main(ActivityThread.java:5417)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at java.lang.reflect.Method.invoke(Native Method)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
04-03 12:53:26.625 14366-14366/com.allianz.azemployee W/System.err:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
04-03 12:53:26.703 14366-14454/com.allianz.azemployee V/RenderScript: 0x9d789000 Launching thread(s), CPUs 4

Это мой класс ActivityRegister.java:

public class ActivityRegister extends AppCompatActivity implements View.OnClickListener {

    Button btnRequestPin, btnConfirm, btnRequestNewPin;
    EditText editTextEmail;
    EditText editTextPin;

    private static final String FIRST_START_KEY = "first_start";
    private static final boolean ALWAYS_SEND_FIRST_START_BROADCAST = false;

    private String emailTemp, tokenTemp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        btnRequestPin = (Button)findViewById(R.id.btn_request_pin);
        btnConfirm = (Button)findViewById(R.id.btn_confirm);
        btnRequestNewPin = (Button)findViewById(R.id.btn_request_newpin);
        editTextEmail = (EditText) findViewById(R.id.editText_mail);
        editTextPin = (EditText) findViewById(R.id.editText_pin);

        btnRequestPin.setOnClickListener(this);
        btnConfirm.setOnClickListener(this);
        btnRequestNewPin.setOnClickListener(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
        Intent intent = new Intent(this,ActivityLogin.class);
        this.startActivity(intent);
    }

    @Override
    public void onClick(View v) {
        if(v == btnConfirm){

            final String email = editTextEmail.getText().toString();
            final String token = editTextPin.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            if (token == null || token.length() == 0){
                Toast.makeText(this,"OTP required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            String postBody = Net.getInstance().getJSONForRegister(email,token);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){

                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.nn"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to register. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if (retCodeInt==0) { //Registration success

                                //Store user-email and token
                                Net.getInstance().saveUserWithValues(ActivityRegister.this, email, token, "");
                                //Take user to login screen.
                                ActivityRegister.this.finish();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for registration. Try again.");
                        }
                    }
                }
            });
        }
        if(v == btnRequestPin || v == btnRequestNewPin){

            final String email = editTextEmail.getText().toString();

            if (email == null || email.length() == 0){
                Toast.makeText(this,"Email required",Toast.LENGTH_SHORT).show();
                return;
            }

            //Check if email is valid
            if(!android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()){
                Toast.makeText(this,"Valid email required.",Toast.LENGTH_SHORT).show();
                return;
            }

            final Button button = (Button) v;
            String postBody = Net.getInstance().getJSONForPinGeneration(email);
            Net.getInstance().callServiceWithURLPart(this, Net.kURLPartEmpAuthentication, postBody, new Net.ICallServiceResult() {
                @Override
                public void serviceResult(String urlPart, boolean expected, String errorMsg) {

                    if(!expected){
                        Log.i("Aditi","errorMsg== " +errorMsg);
                        if(errorMsg!=null){
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.nn"+errorMsg);
                        }
                        else {
                            Net.fastToast(ActivityRegister.this,"Unable to generate pin. Try again.");
                        }
                    }
                    else {
                        try {
                            JSONObject jsonObject = new JSONObject(errorMsg);

                            String retCode = jsonObject.getString("retCode");
                            String status = jsonObject.getString("status");

                            Log.i("Aditi","retCode===" + retCode + " ,status== "+status);
                            Log.i("Aditi","errorMsg== " +errorMsg);

                            int retCodeInt = Integer.parseInt(retCode);
                            Net.fastToast(ActivityRegister.this,status);

                            if(retCodeInt == 0 && button == btnRequestNewPin){

                                ActivityRegister.this.finish(); //take user to login on success.
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                            Net.fastToast(ActivityRegister.this,"Unable to get valid response for pin generation. Try again.");
                        }
                    }

                }
            });
        }
    }
}

Это строка ответа, которую я даю:

public void callServiceWithURLPart(final Activity activity, final String urlPart, final String postBody, final ICallServiceResult callServiceResult){

        final ProgressDialog progress = new ProgressDialog(activity);
        progress.setTitle("Processing..");
        progress.setProgressStyle(android.R.attr.progressBarStyleSmall);
        //progress.setMessage("Connecting...");
        progress.show();

        ConnectivityManager connMgr = (ConnectivityManager)
                activity.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isConnected()) {


            Runnable r = new Runnable() {
                @Override
                public void run() {

                    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).build();

                    try{

                        String servicePath = kURLBase + urlPart;

                        Log.d("OkHttpClient","servicePath = "+servicePath);
                        Log.d("postBody",postBody);

                        Request request = new Request.Builder()
                                .url(servicePath)
                                .put(RequestBody.create(MEDIA_TYPE_JSON, postBody))
                                .build();

                        final Response response = client.newCall(request).execute();
                        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

                        //final String stringResponse = response.body().string();

                        final String stringResponse = "{'serviceName': 'registerToken', 'emailID': '', 'token': ''}";

                        if(stringResponse!=null){
                            Log.d("ServiceResponseString",stringResponse);
                        }else {
                            Log.d("ServiceResponseString","null");
                        }

                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
                                    if(stringResponse!=null){
                                        callServiceResult.serviceResult(urlPart,true,stringResponse);
                                    }
                                    else {
                                        callServiceResult.serviceResult(urlPart,false,stringResponse);
                                    }
                                }
                            });
                        }
                    } catch (Exception e){

                        Log.d("OkHttpClient exception",e.toString());
                        final Exception _e = e;
                        if(callServiceResult!=null){
                            activity.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    progress.dismiss();
           callServiceResult.serviceResult(urlPart,false,_e.toString());
                                }
                            });
                        }
                    }
                }
            };
            Thread t = new Thread(r);
            t.start();
        } else {
            progress.dismiss();
            fastToast(activity,"Connect to internet and try again.");
        }
    }

Мой базовый URL: public static final String kURLBase = "https://api-test.allianz.com/digithonempwebservice/rest";, который предоставляется при запросе stringResponse. Любая помощь будет оценена.

I know that there are several questions posted on here with the same topic and error, but none of them indicate the same problem as mine, so I decided to post my question here, hoping that someone would help me point out the cause.
So I’m trying to implement the login feature in my app and here’s the code:

if (tag.equalsIgnoreCase(login_tag)){
                // check for login response
                try {
                    if (json.getString(KEY_SUCCESS) != null) {
                        String res = json.getString(KEY_SUCCESS);
                        if(Integer.parseInt(res) == 1){
                            // user successfully logged in
                            // Store user details in SQLite Database
                            DatabaseHandler db = new DatabaseHandler(mContext);
                            JSONObject json_user = json.getJSONObject("user");

                            // Clear all previous data in database
                            logoutUser(mContext);
                            Toast.makeText(mContext, json.toString(3), Toast.LENGTH_LONG).show();
                            db.addUser(json_user.getString(KEY_EMAIL), json_user.getString(KEY_NAME), json.getString(KEY_UID), json.getString(KEY_AVA), json_user.getString(KEY_BDAY), json_user.getString(KEY_COUNTRY), json_user.getString(KEY_PREF), json_user.getString(KEY_SPEND));  

                            // Launch Dashboard Screen
                            Intent dashboard = new Intent(mContext, DashboardActivity.class);

                            // Close all views before launching Dashboard
                            dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            mContext.startActivity(dashboard);

                            // Close Login Screen
                            ((Activity) mContext).finish();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

And this is the JSON response I got when logging in:

{
    "tag": "login",
    "success": 1,
    "error": 0,
    "uid": "5123",
    "user": {
        "email": "abcxyz@gmail.com",
        "name": "abc",
        "avatar": "avatars/img_hzsxda_2013-03-18-11-03-33.jpg",
        "bday": "1991-02-01",
        "country": "Australia",
        "preferences": "none",
        "spending": "none"
    }
}

So apparently there is a value for avatar, but I still got this warning in my logcat:

03-18 12:06:36.972: W/System.err(24574): org.json.JSONException: No value for avatar

Since no value avatar is got, I can’t complete addUser, hence login fails.
Please help me find the error and how to solve it. Thank you.

некоторое время искала на сайте, а я никуда не денусь.

Я создаю приложение для Android, которое получает список значений из базы данных mySQL через PHP и возвращает результат, закодированный в объект JSON:

{"error":false,"values":{"1":{"name":"This is a string"}, "2":{...}}}

Я получаю объект JSON в Java следующим образом:

JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");

if (!error) {
JSONObject values = jObj.getJSONObject("values");
Iterator<?> keys = values.keys();

while(keys.hasNext()) {
String key = (String)keys.next();
JSONObject value = jObj.getJSONObject(key);
...
}

Это в точке перед эллипсами, где я получаю исключение:

org.json.JSONException: No value for "1"

Я делаю что-то совершенно глупое, или что-то, все выглядит хорошо для меня. Я пробовал несколько разных вещей, но продолжаю получать одну и ту же проблему.
В конечном итоге я хотел бы получить имя obj и добавить его в список строк. Но я не могу выйти за рамки этой точки.

Любая помощь или толчок в правильном направлении будут благодарны.

0

Решение

JSONObject value = jObj.getJSONObject(key);

Заменить

JSONObject value = values.getJSONObject(key);

1

Другие решения

JSONObject jObj = new JSONObject(response);
boolean error = jObj.getBoolean("error");

if (!error) {
JSONObject values = jObj.getJSONObject("values");
Iterator<?> keys = values.keys();

while(keys.hasNext()) {
String key = (String)keys.next();
JSONObject value = values.getJSONObject(key);
...
}

0

Я получаю следующую строку JSON, которую мне нужно проанализировать:

response => {
    "error":false,
    "uid":39,
    "user":{
        "name":"my username",
        "email":"[email protected]",
        "created_at":"2019-05-15 13:22:19",
        "updated_at":null,
        "imagen":null,
        "nombre":null,
        "apellidos":null,
        "nivel_usuario":null,
        "id_usuario":39,
        "unique_id":null,
        "verified":null,
        "cel_verificado":null,
        "tel":"123456789",
        "code_cel":null
    }
}

Мне нужно получить значения для полей внутри ключевого пользователя.

Я пытаюсь следующим образом, но не работает:

String errorMsg = jObj.getString("error_msg");

Здесь я получаю исключение:

W/System.err: org.json.JSONException: No value for error_msg

и, следовательно, следующие строки не выполняются:

JSONObject jObj = new JSONObject(response);
JSONObject user = jObj.getJSONObject("user");
String email = user.getString("email");

Log.d("RESPUESTA", "RESPUESTA email" + email);

Понравилась статья? Поделить с друзьями:
  • Ошибка json parse error
  • Ошибка opvl ippon smart winner 2000
  • Ошибка json parse anonymous
  • Ошибка opf altivar 31
  • Ошибка jenkins при запуске 1с