2012-01-26 141 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解析之后。

相关问题