1

我是 Android 的新手,所以关于 android 的知识不是很广。

我正在尝试在 android 中实现 Json 调用,我正在使用以下代码来获取数据库中所有用户的列表。

我的 Json.java 如下:-

package com.example.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet= new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();          

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();<----- Getting the value from database
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json); <----- Not able to convertJson value in Json Object
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

我正在使用另一个 java 文件来调用数据库中的值。如下所示:-

package com.example.library;

import java.util.ArrayList;
import java.util.HashMap;

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

import android.app.Activity;
import android.os.Bundle;


public class SecondActivity extends Activity 
{

//url to make request
private static String url = "http://192.168.0.102:3000/users";

// JSON Node names
private static final String TAG_ID = "id";
private static final String TAG_FIRST = "first_name";
private static final String TAG_MIDDLE = "middle_name";
private static final String TAG_LAST = "last_name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_MOBILE = "mobile";

private static final String TAG_USERS = "user";

// users JSONArray
JSONArray users = null;



        @Override

    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_test1);


        // Hashmap for ListView
            ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

            // Creating JSON Parser instance
            JSONParser jParser = new JSONParser();

            // getting JSON string from URL
            JSONArray json = jParser.getJSONFromUrl(url);

            try {
                // Getting Array of Contacts
                users = json.getJSONArray(TAG_USERS);   <---getting error here

                // looping through All Contacts
                for(int i = 0; i < users.length(); i++){
                    JSONObject c = users.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_ID);
                    String first = c.getString(TAG_FIRST);
                    String middle = c.getString(TAG_MIDDLE);
                    String last = c.getString(TAG_LAST);
                    String email = c.getString(TAG_EMAIL);
                    String address = c.getString(TAG_ADDRESS);
                    String mobile = c.getString(TAG_MOBILE);




                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, id);
                    map.put(TAG_FIRST, first);
                    map.put(TAG_MIDDLE,middle);
                    map.put(TAG_LAST, last);
                    map.put(TAG_ADDRESS, address);
                    map.put(TAG_MOBILE, mobile);
                    map.put(TAG_EMAIL, email);

                    // adding HashList to ArrayList
                    contactList.add(map);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

但是在这样做的同时,我在代码中遇到错误,jObj = new JSONObject(json);即我在这里得到一个 Null 值,而我能够从 Json 字符串中的数据库中获取值

我的 Json 调用如下:-

json=[{"admin":null,"card_no":"8789","created_at":"2013-04-09T12:55:54Z","deleted":0,"email":"dfds@fgfd.com","entered_by":null,"first_name":"Gajanan","id":8,"last_name":"Bhat","last_updated_by":null,"middle_name":"","mobile":87981,"updated_at":"2013-04-13T05:26:25Z","user_type_id":null},{"admin":{"created_at":"2013-04-10T09:02:00Z","deleted":0,"designation":"Sr software Engineer","email":"admin@qwe.com","first_name":"Chiron","id":1,"last_name":"Synergies","middle_name":"Sr software Engineer","office_phone":"98789765","super_admin":false,"updated_at":"2013-04-10T12:03:04Z","username":"Admin"},"card_no":"66","created_at":"2013-04-08T09:47:15Z","deleted":0,"email":"rajaarun1991","entered_by":1,"first_name":"Arun","id":1,"last_name":"Raja\n","last_updated_by":1,"middle_name":"Nagarajan","mobile":941,"updated_at":"2013-04-08T09:47:15Z","user_type_id":1}]

我的logcat如下:-

 E/JSON Parser(369): Error parsing data org.json.JSONException: Value [{"user_type_id":null,"middle_name":"","entered_by":null,"card_no":"8789","deleted":0,"id":8,"first_name":"Gajanan","last_updated_by":null,"updated_at":"2013-04-13T05:26:25Z","email":"dfds@fgfd.com","admin":null,"last_name":"Bhat","created_at":"2013-04-09T12:55:54Z","mobile":87981},{"user_type_id":1,"middle_name":"Nagarajan","entered_by":1,"card_no":"66","deleted":0,"id":1,"first_name":"Arun","last_updated_by":1,"updated_at":"2013-04-08T09:47:15Z","email":"rajaarun1991","admin":{"id":1,"first_name":"Chiron","username":"Admin","updated_at":"2013-04-10T12:03:04Z","email":"admin@qwe.com","middle_name":"Sr software Engineer","last_name":"Synergies","designation":"Sr software Engineer","created_at":"2013-04-10T09:02:00Z","super_admin":false,"deleted":0,"office_phone":"98789765"},"last_name":"Raja\n","created_at":"2013-04-08T09:47:15Z","mobile":941}] of type org.json.JSONArray cannot be converted to JSONObject

这个你能帮我吗。

4

2 回答 2

2

JsonJSONArray不是JSONObject

对于参考,JSONObject由 覆盖{}JSONArray覆盖[]

您的返回字符串从[]. 就是这样JSONArray,所以创建一个JSONArray对象。

更改您的代码,

JSONArray jsonArray = new JSONArray(json);
for (int i=0; i < jsonArray.length(); i++)
{
    JSONObject oneObject = jsonArray.getJSONObject(i);

    String oneObjectsItem = oneObject.getString("Key1");
    String oneObjectsItem2 = oneObject.getString("Key2");
}

注意:- 检查null值。

                 oneObject.isNull("key1")

然后赋值。

这是完整的代码。

package com.example.library;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONArray jarray = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONArray getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet= new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();          

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSONArray 
        try {
            jarray = new JSONArray(json); 
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jarray;

    }
}
于 2013-04-27T11:23:11.587 回答
0

您正在尝试获取 Jsonaray 的 jsonobject。检查如何解析 jsonarray,它将解决您的问题。

于 2013-04-27T11:22:09.457 回答