2013-04-27 41 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