如何在java中从json数据获取列表
我的Json数据:如何在java中从json数据获取列表,java,json,api,list,rest,Java,Json,Api,List,Rest,我的Json数据: {'ID':1,'FirstName':'x','LastName':'y','Company':'x','EMail':'x','PhoneNo':'x'} public static void main(String[] args) throws IOException { String json = getJSON().substring(getJSON().indexOf("[")+1,getJSON().indexOf("]")); Users u
{'ID':1,'FirstName':'x','LastName':'y','Company':'x','EMail':'x','PhoneNo':'x'}
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();
}
我的Java代码:
{'ID':1,'FirstName':'x','LastName':'y','Company':'x','EMail':'x','PhoneNo':'x'}
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.google.gson.stream.MalformedJsonException引起:使用JsonReader.setLenient(true)在第1行第136列接受格式错误的JSON
你能帮我吗?对不起,我的英语不好:(请仔细阅读错误消息。该输入不是有效的JSON,这正是消息告诉您的。字符串和键必须用双引号括起来,而不是单引号:
{"ID":1,"FirstName":"x","LastName":"y","Company":"x","EMail":"x","PhoneNo":"x"}
一个简单的检查也会告诉你同样的情况。或者,正如错误消息方便地告诉你的那样,你可以将阅读器设置为宽容,希望接受格式错误的JSON作为输入