2012-01-26 127 views
0
class Talk { 
     String[] values; 
     try { 
      InputStream is = getAssets().open("jdata.txt"); 
      DataInputStream in = new DataInputStream(is); 
      BufferedReader br = new BufferedReader(new InputStreamReader(in)); 

      //Read File Line By Line 
      while ((br.readLine()) != null) { 
       // Print the content on the console 
       strLine = strLine + br.readLine(); 
      } 
     } catch (Exception e) { //Catch exception if any 
      System.err.println("Error: " + e.getMessage()); 
     } 
     parse(strLine); 
    } 

    public void parse(String jsonLine) { 
     Data data = new Gson().fromJson(jsonLine, Data.class); 
     values[0]= data.toString(); 
     return; 
    } 
} 

這是jdata.txtjava.lang.IllegalStateException:預期BEGIN_OBJECT錯誤

"{" + "'users':'john' + "}" 

這是我Data.java

public class Data { 
    public String users; 
} 

我得到的錯誤是:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 9 

任何人都可以對我而言,這個錯誤意味着什麼以及如何刪除它?編號:

我得到了答案。這些是我必須做的調整。首先,將字符串數組更改爲數組列表。

List<String> values = new ArrayList<String>(); 

下的調整是在這裏:

strLine = currentLine; 
       currentLine = br.readLine(); 
       //Read File Line By Line 
       while (currentLine != null) { 
       // Print the content on the console 

        strLine = strLine + currentLine; 
        currentLine = br.readLine(); 
       } 

最後的調整在這裏:

String val = data.toString(); 
values.add(val); 

代碼的某些部分可能是多餘的,但後來我會照顧那個。

+0

你的json無效這是正確的json格式'{「users」:「john」 }' – RanRag 2012-01-26 22:51:14

+0

@RanRag試過了。沒有工作。所以改變它試圖獲得正確的結果。 – Hick 2012-01-26 22:52:38

回答

1

您打給readLine()兩次。以下將導致被從文件中讀取一行,失去了:

while ((br.readLine()) != null) { 

更改環路:

//Read File Line By Line 
String currentLine = br.readLine(); 
while (currentLine != null) { 
    // Print the content on the console 
    strLine = strLine + currentLine; 
    currentLine = br.readLine(); 
} 

而且,jdata.txt內容應該是:

{"users":"john"} 

無多餘的+"個字符。

+0

是否做到了。仍然錯誤仍然存​​在。 – Hick 2012-01-26 23:07:24

+0

你試過調試過嗎?你確認你傳給Gson的字符串是正確的嗎?由於Gson是開源的,你也可以調試他們的代碼。 – 2012-01-26 23:09:30

+0

我調試過了。代碼在這行之後中斷:Data data = new Gson()。fromJson(jsonLine,Data.class); – Hick 2012-01-26 23:20:04

0

除了@Eli提到的問題。

這是使用Gson Library解析json的方式。現在

Gson gson = new Gson(); 
Data data = gson.fromJson(jsonLine, Data.class); 
System.out.println("users:" + data.getusers()); 

我Data.java文件

public class Data { 

public String users; 

public String getusers() { 
return users; 
     } 

輸出=

JSonString在jdata.txt = { 「用戶」: 「約翰」}

用戶:約翰//在json解析之後。

相關問題