VkApi。 JSONException

时间:2014-10-30 15:11:59

标签: android vk jsonexception

我想显示我朋友的列表。我不明白为什么String无法转换为json。我理解152(MainActivity)中的错误

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

但我不知道为什么......

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

在日志中,此响应显示响应:

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

JSON如何看起来像VK服务器

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
    }]
 }

我的主要活动

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) {
}}

我的模特朋友

  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;
} }

错误

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":"За

1 个答案:

答案 0 :(得分:2)

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

应该是这样的:

JSONObject o = new JSONObject(response.responseString);

因为您正在尝试将对象转换为字符串。它的toString方法将返回com.vk.sdk.api.VKResponse@42b40ac0,而不是json。

修改 简单地说:

您的JSON是一个对象。所以你可以先解析它:JSONObject o = new JSONObject(response.toString());。如果你想得到所有的朋友,你需要迭代它里面的数组。

为此你可以这样做:

JSONArray jsonArray = o.getJSONArray("items"); //the array is "items" not response.
 for (int i = 0; i < jsonArray.length(); i++) { //simple iteration
      JSONObject jsonObject = jsonArray.getJSONObject(i); //this contains 1 item
      Friend fr = new Friend();
      fr.setFirst_name(jsonObject.getString("first_name"));
      fr.setLast_name(jsonObject.getString("last_name"));
      fr.setSex(jsonObject.getString("sex")); //sex is an integer so you might want to change this
      //fr.setBdate(jsonObject.getString("bdate"));//there is no such field "bdate" on this json
      fr.setCity(jsonObject.getJSONObject("city").getString("title")); //city is an object. Not a string
      friendArrayList.add(fr);
 }

这是简单的JSON解析,您应该能够自己完成。您可能无法理解您可能想要开始阅读一些教程背后的结构。这是一个很好的起点:http://www.javacodegeeks.com/2013/10/android-json-tutorial-create-and-parse-json-data.html