如何在java中从json数据中获取列表
我的Json数据:
{'ID':1,'FirstName':'x','LastName':'y','Company':'x','EMail':'x','PhoneNo':'x'}
我的Java代码:
public static void main(String[] args) throws IOException {
String json = getJSON().substring(getJSON().indexOf("[")+1,getJSON().indexOf("]"));
Users user = new Gson().fromJson(json, Users.class);
WriteLine("["+user.getID()+"]"+" "+user.getFirstName()+" "+user.getLastName()+" "+user.getCompany()+" "+user.getEMail()+" "+user.getPhoneNo());
}
static void WriteLine(String text){
System.out.print(text);
}
static String getJSON() throws IOException
{
URL url = new URL("http://localhost:51679/api/User");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sBuilder = new StringBuilder();
String line;
while((line = reader.readLine()) != null){
sBuilder.append(line);
}
reader.close();
connection.disconnect();
return sBuilder.toString();
}
但我的json数据如下:
{'ID':1,'FirstName':'x','LastName':'x','Company':'x','EMail':'x','PhoneNo':'x'},{'ID':2,'FirstName':'y','LastName':'y','Company':'y','EMail':'x','PhoneNo':'y'}
我有一个错误:由:com引起。谷歌。格森。流动格式错误的JSONException:使用JsonReader。setLenient(true)在第1行第136列接受格式错误的JSON
你能帮我吗?抱歉我的英语不好:(
# 1 楼答案
仔细阅读错误消息该输入不是有效的JSON,这正是消息告诉您的。字符串和键必须用双引号括起来,而不是单引号:
用a JSON validator简单检查一下也会得出同样的结果。或者,正如错误消息方便地告诉您的那样,您可以将读取器设置为对^{} 宽容,希望接受格式错误的JSON作为输入