2017-06-04 84 views
0

我建立在使用JSON接取到我的PostgreSQL的Android Studio中的应用,在那里是我的数据,我收到的数据是这样的:阅读在Android Studio中的JSON数据

[ 
{"id":"1","title":"12 May to 30 Jun"}, 
{"id":"2","title":"3 Jun to 20 Jun"} 
] 

我试图找到每其中,如何使用的JSONObject或JSONArray为“解锁”的数据传给其他变量

+0

https://stackoverflow.com/questions/25582199/sending-arraylist-from-android-to-php-script-using-json – Jamil

回答

0

一段时间努力,努力,我发现了一种

      String finalJson = buffer.toString(); 

      try { 
       JSONArray parentArray = new JSONArray(finalJson); 

       int count = 0; 
       int[] id = new int[parentArray.length()]; 
       String[] title = new String[parentArray.length()]; 
       StringBuffer finalBufferedData = new StringBuffer(); 
       while (count < parentArray.length()) 
       { 

        JSONObject finalObject = parentArray.getJSONObject(count); 
        id[count] = finalObject.getInt("id"); 
        title[count] = finalObject.getString("title"); 
        finalBufferedData.append(id[count] + " - " + title[count] + "\n"); 
        count++; 

       } 
       return finalBufferedData.toString(); 


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

这样我就能够GE之后从PostgreSQL的t为2行显示它(以后将​​增加它的应用程序源码,因此并不需要总是在我的PostgreSQL检查)

0

这里是工作代码:

public void parseJson() { 

    // Response from API call 
    String response = "[{\"id\":\"1\",\"title\":\"12 May to 30 Jun\"},\n" + 
         "{\"id\":\"2\",\"title\":\"3 Jun to 20 Jun\"}]"; 

    try { 
     JSONArray jsonArray = new JSONArray(response); 

     // Get all jsonObject from jsonArray 
     for (int i = 0; i < jsonArray.length(); i++) 
     { 
      JSONObject jsonObject = jsonArray.getJSONObject(i); 

      String id = null, title = null; 

      // Id 
      if (jsonObject.has("id") && !jsonObject.isNull("id")) { 
       id = jsonObject.getString("id"); 
      } 

      // Title 
      if (jsonObject.has("title") && !jsonObject.isNull("title")) { 
       title = jsonObject.getString("title"); 
      } 

      Log.d("SUCCESS", "JSON Object: " + "\nId: " + id 
              + "\nTitle: " + title); 
     } 
    } catch (JSONException e) { 
     Log.e("FAILED", "Json parsing error: " + e.getMessage()); 
    } 
} 

OUTPUT:

D/SUCCESS: JSON Object: 
      Id: 1 
      Title: 12 May to 30 Jun 

D/SUCCESS: JSON Object: 
      Id: 2 
      Title: 3 Jun to 20 Jun