如何从java中的json数据获取列表

时间:2013-06-25 23:00:50

标签: java json api list rest

我的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.google.gson.stream.MalformedJsonException:使用JsonReader.setLenient(true)接受第1行第136列格式错误的JSON

你能帮帮我吗?抱歉我的英文不好:(

1 个答案:

答案 0 :(得分:0)

仔细阅读错误消息。 该输入无效JSON,,这正是消息告诉您的内容。字符串和键必须用双引号包围,而不是单引号:

{"ID":1,"FirstName":"x","LastName":"y","Company":"x","EMail":"x","PhoneNo":"x"}

使用a JSON validator进行简单检查会告诉您相同的情况。或者 - 再次,正如错误消息方便地告诉您 - 您可以将阅读器设置为对JsonReader.setLenient(true)宽容,以期希望接受格式错误的JSON作为输入。