我需要从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“,”客户“:” abc“}]
此代码不显示返回的JSON数组的城市名称。有人可以通过更正代码来帮助我解决这个问题,或者提出更好或更容易的方法(如果有)吗? :)
最佳答案
Nikita已经为您提供了正确的解决方案,但是这里就是逐步的解决方案。
我将您的问题简化为此最小测试:
import com.google.gson.Gson;
public class TestGSON
{
public static void main( String[] args )
{
// that's your JSON sample
String json = "[{\"reserve_no\":\"20\",\"city\":\"city2\",\"street\":\"street1234\",\"discription\":\"discription123\",\"date\":\"2012-10-22 04:47:54\",\"customer\":\"abc\"}]";
// note: we tell Gson to expect an **array** of Data
Data data[] = new Gson().fromJson(json, Data[].class);
System.out.println(data[0]);
}
}
问题在于您的JSON片段实际上是对象的数组,而不仅仅是对象(因此,其周围是[])。因此,您需要告诉GSon它必须期望一个数据数组,而不仅仅是一个数据对象。顺便说一句,按原样执行代码时引发的异常已经告诉您了:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2
除非它被一个空的
catch
块吞没了关于Data类:在重写toString方法之前,请三思而后行。我会放弃该方法而只是做
System.out.println( data[0].getCity() );
关于java - 如何将值从json数组转换为java字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13020109/