JSON配列から値を取得して表示する必要があります。以下は私が使用したコードです。
getresponse
クラスはHTTPリクエストをPHPページに送信し、関連するJSON配列を取得し、パブリック変数resは返されたJSON配列を保持します。
public class JSONConverter {
public void convert(){
getresponse gr=new getresponse();
String json = gr.res;
Data data = new Gson().fromJson(json, Data.class);
System.out.println(data);
}
}
class Data {
private String city;
private int reserve_no;
public String getCity() { return city; }
public int getReserve_no() { return reserve_no; }
public void setTitle(String city) { this.city = city; }
public void setId(int reserve_no) { this.reserve_no = reserve_no; }
public String toString() {
return String.format(city);
}
}
getresposeクラス
public class getresponse {
public static String res;
public void counter() {
try {
URL url = new URL("http://taxi.net/fetchLatest.php");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String str;
while ((str =br.readLine()) != null) {
res=str;
}
conn.disconnect();
以下は、返されるJSON配列の例です。
[{"reserve_no": "20"、 "city": "city2"、 "street": "street1234"、 "discription": "discription123"、 "date": "2012-10-22 04:47:54" 、"customer": "abc"}]
このコードは、返されたJSON配列の都市名を表示しません。誰かがコードを修正することによってこれを手伝ってくれるか、もしあればより良いまたはより簡単な方法を提案できますか?:)