Json文件没有被读取 - Java / Gson

时间:2012-10-16 14:17:39

标签: java json gson

我整理了几行代码来使用Google的GSON Library阅读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(){
            }

}

supertweet

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

提前致谢!

1 个答案:

答案 0 :(得分:0)

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

尝试更改代码:

//you need to create this object
TweetObject J_tweet = (TweetObject) gson.fromJson(bufferedReader, type);