我建立在使用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爲「解鎖」的數據傳給其他變量
我建立在使用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爲「解鎖」的數據傳給其他變量
一段時間努力,努力,我發現了一種
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檢查)
這裏是工作代碼:
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
https://stackoverflow.com/questions/25582199/sending-arraylist-from-android-to-php-script-using-json – Jamil