我需要从 JSON 数组中获取值并显示它们。下面是我使用的代码。
getresponse
类将向 PHP 页面发送 HTTP 请求并获取相关的 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" "客户":"abc"}]
此代码不显示返回的 JSON 数组的城市名称。有人可以通过更正代码或建议更好或更简单的方法来帮助我吗?:)