2012-09-13 278 views
1

我想從一個字符串創建json對象,該字符串作爲來自服務器中servlet的響應。將字符串轉換爲json對象

public class JSONParser { 

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

// constructor 
public JSONParser() { 

} 

    public JSONObject getJSONFromUrl(String url,String a) { 

     ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
     postParameters.add(new BasicNameValuePair("branchname", a)); 

     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(url); 
      httppost.setEntity(new UrlEncodedFormEntity(postParameters)); 

      HttpResponse httpResponse = httpClient.execute(httppost); 
      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 JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 


     return jObj;    
}} 

這是我的servlet ..

public class AvailabilityResponse extends HttpServlet { 

@Override 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
    throws ServletException, IOException { 

    PrintWriter out=response.getWriter(); 

     String br_id; 
     br_id=request.getParameter("branchname"); 

    try{ 
       Class.forName("com.mysql.jdbc.Driver").newInstance(); 
       Connection con=DriverManager.getConnection("jdbc:mysql://localhost:8888 /atmlivedetails","root","root"); 
     Statement st=con.createStatement(); 
     ResultSet rs=st.executeQuery("select atmbrno, atmbrname from location_stat where act_brname='"+br_id+"'"); 
     int i=0; 
     JSONArray jArray = new JSONArray(); 
     while(rs.next()){ 

    String s = rs.getString("atmbrno"); 
    String t = rs.getString("atmbrname"); 

    JSONObject arrayObj = new JSONObject(); 

    arrayObj.put("atmbrno",s); 
    arrayObj.put("atmbrname",t); 

    jArray.add(i,arrayObj); 
    i++; 
    } 
    rs.close(); 
    st.close(); 
    out.print(jArray); 
} 

    catch(Exception e){ 
      out.print(e); 
    } 


}} 

但是當我運行這個它說錯誤

"parsing data org.json.JSONException: Value [{"atmbrname":"ANURADAPURA 
[ATM 2]","atmbrno":"ATM084"},{"atmbrname":"MANNAR BRANCH 
","atmbrno":"ATM344"}] of type org.json.JSONArray cannot be converted 
to JSONObject" 

什麼是錯在這種情況下?

這裏是我調用類

public class ListAtmActivity extends ListActivity{ 

private static String url ="http://10.0.2.2:8080/hello/AvailabilityResponse"; 

//TextView error; 
//String brName; 

//Bundle b = getIntent().getExtras(); 
//String brName = b.getString("key"); 

private static final String TAG_CONTACTS = "contacts"; 
private static final String TAG_ID = "id"; 
private static final String ATM_NO = "atmbrno"; 
private static final String ATM_PLACE = "atmbrname"; 

// contacts JSONArray 
//JSONArray contacts = null; 

@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.list_item); 

    String brName=getIntent().getExtras().getString("key"); 


    /*Bundle b = getIntent().getExtras(); 
    brName = b.getString("key"); 
    */ 


    // 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 
    JSONObject json = jParser.getJSONFromUrl(url,brName); 


    try{ 
     //String results; 
     JSONArray contacts = json.getJSONArray(TAG_CONTACTS); 

     for(int i = 0; i < contacts.length(); i++){ 
      JSONObject json_data = contacts.getJSONObject(i); 

      // Storing each json item in variable 
      String atm_id = json_data.getString(ATM_NO); 
      String atm_name = json_data.getString(ATM_PLACE); 

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

      map.put(ATM_NO, atm_id); 
      map.put(ATM_PLACE, atm_name); 

      contactList.add(map);     
     }      
    } 

    catch(JSONException e) { 
     e.printStackTrace(); 

    } 

    /** 
    * Updating parsed JSON data into ListView 
    * */ 
    ListAdapter adapter = new SimpleAdapter(this, contactList, 
      R.layout.list_main, 
      new String[] { ATM_NO, ATM_PLACE }, new int[] { 
        R.id.name , R.id.email }); 

    setListAdapter(adapter); 

}} 
+0

因爲你發送一個JSON數組只是改變了JSON對象行JSON數組則允許所有操作或者aadan {在前面和}在檢索到的字符串結尾它將doo –

+0

我認爲問題來自servlet返回數組..它可能不會根據正確的格式..但我不明白什麼是錯了嗎? – Dasaya

+0

@ droidhot-可以糾正錯誤..我不能得到它 – Dasaya

回答

1

你可以改變JSON對象JSON數組,

public class JSONParser { 

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

// constructor 
public JSONParser() { 

} 

    public JSONArray getJSONFromUrl(String url,String a) { 

     ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
     postParameters.add(new BasicNameValuePair("branchname", a)); 

     try { 
      // defaultHttpClient 
      DefaultHttpClient httpClient = new DefaultHttpClient(); 
      HttpPost httppost = new HttpPost(url); 
      httppost.setEntity(new UrlEncodedFormEntity(postParameters)); 

      HttpResponse httpResponse = httpClient.execute(httppost); 
      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 JSON Array 
     try { 
      jObj = new JSONArray(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 


     return jObj;    
}} 

你返回的數據是JSON數組,但你轉換JSON對象,這是唯一的例外加薪。

static JSONArray jObj = null; 

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

你需要JsonArray來解析得到的字符串,基本上你得到JsonArray在你的Response。

JSONArray jObj = null; 

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

按您的要求發佈

public class JSONParser { 

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

    // constructor 
    public JSONParser() { 

    } 

public JSONArray getJSONFromUrl(String url,String a) { 

    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
    postParameters.add(new BasicNameValuePair("branchname", a)); 

    try { 
     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(url); 
     httppost.setEntity(new UrlEncodedFormEntity(postParameters)); 

     HttpResponse httpResponse = httpClient.execute(httppost); 
     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 JSON object 
    try { 
     jObj = new JSONArray(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 


    return jObj;    
    }} 

,並在解析類

public class ListAtmActivity extends ListActivity{ 

private static String url ="http://10.0.2.2:8080/hello/AvailabilityResponse"; 

//TextView error; 
    //String brName; 

    //Bundle b = getIntent().getExtras(); 
//String brName = b.getString("key"); 

private static final String TAG_CONTACTS = "contacts"; 
private static final String TAG_ID = "id"; 
private static final String ATM_NO = "atmbrno"; 
static final String ATM_PLACE = "atmbrname"; 

// contacts JSONArray 
    //JSONArray contacts = null; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.list_item); 

String brName=getIntent().getExtras().getString("key"); 


/*Bundle b = getIntent().getExtras(); 
brName = b.getString("key"); 
*/ 


// 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 contacts = jParser.getJSONFromUrl(url,brName); 


try{ 
    //String results; 


    for(int i = 0; i < contacts.length(); i++){ 
     JSONObject json_data = contacts.getJSONObject(i); 

     // Storing each json item in variable 
     String atm_id = json_data.getString(ATM_NO); 
     String atm_name = json_data.getString(ATM_PLACE); 

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

     map.put(ATM_NO, atm_id); 
     map.put(ATM_PLACE, atm_name); 

     contactList.add(map);     
    }      
} 

catch(JSONException e) { 
    e.printStackTrace(); 

} 

    /** 
    * Updating parsed JSON data into ListView 
    * */ 
    ListAdapter adapter = new SimpleAdapter(this, contactList, 
     R.layout.list_main, 
     new String[] { ATM_NO, ATM_PLACE }, new int[] { 
       R.id.name , R.id.email }); 

    setListAdapter(adapter); 

    }} 
+0

謝謝你非常多..我會嘗試這一點,並告訴結果..希望這將工作.. – Dasaya

+0

它的工作...非常感謝你..沒有錯誤,但仍然Listview不會發生..我必須與.. .. ! – Dasaya

+0

;)開心是能夠幫助:) –