0

我整理了几行代码来使用 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.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);
        }
    }
}

鸣叫

public class tweet {
    String from_user;
    String from_user_name;
    String profile_image_url;
    String text;

    public tweet(){
            }

}

超级推文

import java.util.ArrayList;


public class supertweet {
    ArrayList<tweet> result;

    public supertweet(){

        result = new ArrayList<tweet>();
    }

    public void setResult(ArrayList<tweet> result)
    {
        result = result;
    }
}

添加 Json 会占用太多空间,所以这里是链接。 http://pastebin.com/rPrbfPMb

提前致谢!

4

1 回答 1

0

您在实际获取对象时尝试将 Json 转换为数组。

尝试更改您的代码:

//you need to create this object
TweetObject J_tweet = (TweetObject) gson.fromJson(bufferedReader, type);
于 2012-10-16T14:22:38.057 回答