未读取Json文件-Java/Gson
我使用Google的GSON库编写了几行代码来读取Json,但在运行时收到了一个错误。我不确定它是什么,但我怀疑它可能是json的格式 错误:未读取Json文件-Java/Gson,java,json,gson,Java,Json,Gson,我使用Google的GSON库编写了几行代码来读取Json,但在运行时收到了一个错误。我不确定它是什么,但我怀疑它可能是json的格式 错误: Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2 at com.google.gs
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
at com.google.gson.Gson.fromJson(Gson.java:806)
at com.google.gson.Gson.fromJson(Gson.java:761)
at tweetfeedreader.main(tweetfeedreader.java:18)
Caused by: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2
at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
at com.google.gson.stream.JsonReader.beginArray(JsonReader.java:306)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:79)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
at com.google.gson.Gson.fromJson(Gson.java:795)
... 2 more
代码:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.lang.reflect.Type;
import java.util.ArrayList;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class tweetfeedreader {
public static void main(String args[]) throws FileNotFoundException {
ArrayList<tweet> tCollection = new ArrayList<tweet>();
Gson gson = new Gson();
BufferedReader bufferedReader = new BufferedReader(new FileReader(
"C:/Users/DX029/Desktop/jsonfile.txt"));
Type type = new TypeToken<ArrayList<tweet>>(){}.getType();
ArrayList J_tweet = (ArrayList<tweet>)gson.fromJson(bufferedReader, type);
supertweet sup = new supertweet();
for(tweet t: sup.result){
System.out.println(t.text);
}
}
}
超级推特
import java.util.ArrayList;
public class supertweet {
ArrayList<tweet> result;
public supertweet(){
result = new ArrayList<tweet>();
}
public void setResult(ArrayList<tweet> result)
{
result = result;
}
}
import java.util.ArrayList;
公共类超级推特{
阵列列表结果;
公共超级推特(){
结果=新的ArrayList();
}
公共void setResult(ArrayList结果)
{
结果=结果;
}
}
添加Json会占用太多的空间,下面是链接。
提前谢谢 在实际获取对象时,您正在尝试将Json转换为数组 尝试更改您的代码:
//you need to create this object
TweetObject J_tweet = (TweetObject) gson.fromJson(bufferedReader, type);
您也会遇到一个问题,即没有引号的键。
//you need to create this object
TweetObject J_tweet = (TweetObject) gson.fromJson(bufferedReader, type);