2013-04-27 86 views
1

我是Android中的新蜂,因此有關android的知識並不是很多。無法將Json值轉換爲Json對象

我想在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文件來調用該值從database.It如下: -

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);這是我得到一個空值,而我能夠從數據庫中獲取Json字符串的值

我的Json調用是一個小號如下: -

json=[{"admin":null,"card_no":"8789","created_at":"2013-04-09T12:55:54Z","deleted":0,"email":"[email protected]","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":"[email protected]","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":"[email protected]","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":"[email protected]","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 

請幫我出這一點。

+0

發佈您的logcat和json。 – rajeshwaran 2013-04-27 11:13:02

+0

@rajeshwaran我有更新的代碼,請檢查它 – Catmandu 2013-04-27 11:22:12

+0

你看到我的答案嗎? – rajeshwaran 2013-04-27 11:39:26

回答

1

您的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; 

    } 
} 
+0

我不想將Json字符串轉換爲Json對象。我嘗試過,但它不工作..你有什麼建議 – Catmandu 2013-04-27 11:40:12

+0

你字符串JSON是JSONArray不是JSONObject,所以你的返回字符串是轉換爲JSONArray – rajeshwaran 2013-04-27 11:42:23

+0

我已經更新了問題。請檢查它 – Catmandu 2013-04-29 04:17:54

0

您正試圖獲得Jsonaray的jsonobject 。請檢查如何解析jsonarray,它會解決您的問題。

+0

這是錯誤的方法。我沒有意識到這一點,因爲我剛剛開始在Android編碼..你可以幫我 – Catmandu 2013-04-27 11:23:51

+0

是的。谷歌Android解析jsonarray,你會得到很多的例子。 – 2013-04-27 11:27:11