2014-09-27 98 views
3

我嘗試開發一個Android應用程序的Web服務返回一個JSON文件,例如:閱讀JSON通過web服務的Android

{ 「成功」:1, 「消息」: 「後 可用」, 「posts」:[{「post_id」:「1」,「username」:「hasni」,「title」:「titre」,「message」:「這個 是我的信息」},{「post_id」:「2 「,」username「:」user2「,」title「:」titre 2「,」message「:」這是我的信息 2「},{」post_id「:」3「,」username「:」123「 「標題」: 「12」, 「消息」: 「111」},{ 「POST_ID」: 「4」, 「用戶名」: 「1212」, 「標題」: 「1212」, 「消息」: 「1212」 },{「post_id」:「5」,「username」:「1212」,「title」:「bonjour」,「message」:「voila ce message qui dient d'une session 「},{」 POST_ID 「:」 6" , 「用戶名」: 「121212」, 「標題」: 「滴度」, 「消息」: 「消息」}]}

這是部分讀取此JSON的代碼:

 // Building Parameters 
     List<NameValuePair> params = new ArrayList<NameValuePair>(); 
     params.add(new BasicNameValuePair("receiver", strSender)); 
     JSONObject json = jsonParser.makeHttpRequest(
       LOGIN_URL, "POST", params); 
     success = json.getInt(TAG_SUCCESS); 

     Log.d("ok", "ok"); 

     if (success == 1){ 

      messagesArray = (JSONArray)json.getJSONArray(TAG_POSTS); 
      for (int i= 0;i <messagesArray.length();i++){ 
       Log.d("iteration", "iteration" + i); 
       JSONObject messageJson = messagesArray.getJSONObject(i); 
       Log.d("post_id","post_id: "+i+ " "+ messageJson.getString(TAG_POSTS_ID)); 
       Log.d("username","username: " +i+" " + messageJson.getString(TAG_POSTS_USERNAME)); 
       Log.d("title", "title: " +i+ " " + messageJson.getString(TAG_POSTS_ID_TITLE)); 
       Log.d("message","message: "+i+" "+ messageJson.getString(TAG_POSTS_ID_MESSAGE)); 
      } 

     }else{ 
      Log.d("failed", "!!!!!!!!!!!!!!!!!!!!!!!!"); 
     } 

但我遇到問題:應用程序崩潰並退出。這是logcat的:

09-27 23:15:37.119:W/System.err的(489):org.json.JSONException:15:37.119:上崗09-27 23號 值W /System.err(489):at org.json.JSONObject.get(JSONObject.java:354)09-27 23:15:37.128: W/System.err(489):at org.json.JSONObject .getJSONArray(JSONObject.java:544)09-27 23:15:37.128:W/System.err(489):at com.example.mysql.ReadMessages.onCreate(ReadMessages.java:73)09-27 23:15:37.128:W/System.err(489):at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047) 09-27 23:15:37.128:W/Syst em.err(489):at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611) 09-27 23:15:37.128:W/System.err(489):at android.app.ActivityThread。 (活動線程.java:1663) 09-27 23:15: 15:37.128:W/System.err(489):at android.app.ActivityThread $ H.handleMessage(ActivityThread.java:931) 09-27 23:15:37.138:W/System.err(489):在 android.os.Handler.dispatchMessage(Handler.java:99)09-27 23:15:37.138:W/System.err(489):at android.os.Looper.loop(Looper.java:123 )09-27 23:15:37.138: W/System.err(489):at android.app.ActivityThread.main(ActivityThread.java:3683)09-27 23:15:37.138:W/System.err(489):at java.lang .reflect.Method.invokeNative(Native Method)09-27 23:15:37.138:W/System.err(489):at java.lang.reflect.Method.invoke(Method.java:507)09-27 23:15:37.138: W/System.err(489):at com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:839) 09-27 23:15:37.138:W/System.err(489):at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)09-27 23:15:37.138:W/System.err(489):at dalvik。 system.NativeStart。主(本地方法)

+0

你能打印的Android收到的JSON?嘗試編碼Log.d(「json」,json.toString());'below' success = json.getInt(TAG_SUCCESS);'並告訴json收到的結構是否如你所期望的那樣。 – RdlP 2014-09-27 01:01:03

回答

1

我想你的代碼,這樣一來,

private void jsonTest() { 
    try { 
     String jsonString = "{\"success\":1,\"message\":\"Post Available!\",\"posts\":[{\"post_id\":\"1\",\"username\":\"hasni\",\"title\":\"titre\",\"message\":\"this is my message\"},{\"post_id\":\"2\",\"username\":\"user2\",\"title\":\"titre 2\",\"message\":\"this is my message 2\"},{\"post_id\":\"3\",\"username\":\"123\",\"title\":\"12\",\"message\":\"111\"},{\"post_id\":\"4\",\"username\":\"1212\",\"title\":\"1212\",\"message\":\"1212\"},{\"post_id\":\"5\",\"username\":\"1212\",\"title\":\"bonjour\",\"message\":\"voila ce message qui vient d'une session \"},{\"post_id\":\"6\",\"username\":\"121212\",\"title\":\"titre\",\"message\":\"message\"}]}"; 

     Log.i(TAG, "jsonString = " + jsonString); 
     JSONObject json = new JSONObject(jsonString); 
     int success = json.getInt("success"); 

     Log.d("ok", "ok"); 

     if (success == 1) { 

      JSONArray messagesArray = (JSONArray) json 
        .getJSONArray("posts"); 
      for (int i = 0; i < messagesArray.length(); i++) { 
       Log.d("iteration", "iteration" + i); 
       JSONObject messageJson = messagesArray.getJSONObject(i); 
       Log.d("post_id", 
         "post_id: " + i + " " 
           + messageJson.getString("post_id")); 
       Log.d("username", 
         "username: " + i + " " 
           + messageJson.getString("username")); 
       Log.d("title", 
         "title: " + i + " " 
           + messageJson.getString("title")); 
       Log.d("message", 
         "message: " + i + " " 
           + messageJson.getString("message")); 
      } 

     } else { 
      Log.d("failed", "!!!!!!!!!!!!!!!!!!!!!!!!"); 
     } 
    } catch (Exception e) { 
     // TODO: handle exception 
     e.printStackTrace(); 
    } 
} 

而且工作正常,可能是壞了,你定義你的標籤。

+0

我這在json解析器中有問題 – 2014-09-27 16:22:53

-1

認爲,代碼工作正常,但 我這個問題的起源是在JSON解析器

package com.example.mysql; 

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

import org.apache.http.HttpEntity; 
import org.apache.http.HttpResponse; 
import org.apache.http.NameValuePair; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.entity.UrlEncodedFormEntity; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.client.methods.HttpPost; 
import org.apache.http.client.utils.URLEncodedUtils; 
import org.apache.http.cookie.Cookie; 
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 = ""; 
    DefaultHttpClient httpClient = new DefaultHttpClient(); 
    List<Cookie> cookies = httpClient.getCookieStore().getCookies(); 


    // constructor 
    public JSONParser() { 

    } 

    // function get json from url 
    // by making HTTP POST or GET mehtod 
    public JSONObject makeHttpRequest(String url, String method, 
      List<NameValuePair> params) { 

     // Making HTTP request 
     try { 

      // check for request method 
      if(method == "POST"){ 
       // request method is POST 
       // defaultHttpClient 
       HttpPost httpPost = new HttpPost(url); 
       httpPost.setEntity(new UrlEncodedFormEntity(params)); 

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

      }else if(method == "GET"){ 
       // request method is GET 
       String paramString = URLEncodedUtils.format(params, "utf-8"); 
       url += "?" + paramString; 
       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 JSON object 
     try { 
      jObj = new JSONObject(json); 
     } catch (JSONException e) { 
      Log.e("JSON Parser", "Error parsing data " + e.toString()); 
     } 

     // return JSON String 
     return jObj; 

    } 
}