java.lang.IllegalStateException:应为BEGIN\u对象错误
这在java.lang.IllegalStateException:应为BEGIN\u对象错误,java,Java,这在jdata.txt中: class Talk { String[] values; try { InputStream is = getAssets().open("jdata.txt"); DataInputStream in = new DataInputStream(is); BufferedReader br = new BufferedReader(new InputStream
jdata.txt
中:
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;
}
}
这是我的数据。java
:
"{" + "'users':'john' + "}"
我得到的错误是:
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();
}
代码的某些部分可能是多余的,但我稍后会处理 您正在调用
readLine()
两次。以下情况会导致从文件中读取一行并丢失:
String val = data.toString();
values.add(val);
将循环更改为:
while ((br.readLine()) != null) {
另外,jdata.txt
的内容应该是:
//Read File Line By Line
String currentLine = br.readLine();
while (currentLine != null) {
// Print the content on the console
strLine = strLine + currentLine;
currentLine = br.readLine();
}
没有多余的
+
或“
字符。除了@Eli提到的问题
这是使用Gson库解析json的方法
{"users":"john"}
现在是我的Data.java文件
Gson gson = new Gson();
Data data = gson.fromJson(jsonLine, Data.class);
System.out.println("users:" + data.getusers());
输出=
jdata.txt中的JSonString={“用户”:“john”}
用户:john//json解析后
您的json无效这是正确的json格式
{“users”:“john”}
@RanRag已经尝试过了。不起作用。因此,为了得到正确的结果,对其进行了更改。您尝试过调试吗?您验证了传递给Gson的字符串是否正确吗?由于Gson是开源的,您也可以调试到他们的代码中。我已经调试过。代码在这一行之后中断:Data Data=new Gson()。fromJson(jsonLine,Data.class);和?jsonLine的值是否正确?您是否尝试从json()进入fromJson()
?啊!等等!我的错误。再次调试。我的strLine似乎只有null。
public class Data {
public String users;
public String getusers() {
return users;
}