2013-06-25 28 views
-1

我的JSON數據:如何讓從Java 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.goog le.gson.stream.MalformedJsonException:使用JsonReader.setLenient(true)在第1行接受格式錯誤的JSON 136

您能幫助我嗎?對不起,我的英語不好:(

回答

0

仔細閱讀錯誤消息。該輸入是不是有效的JSON,這正是消息告訴你。字符串和密鑰必須與雙引號,沒有單引號包圍:

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

a JSON validator一個簡單的檢查會告訴你同樣的或者 - 再次,作爲錯誤信息方便地告訴你 - 你可以設置讀者手下留情與JsonReader.setLenient(true),對希望接受畸形的JSON作爲輸入。