找到如何解析json格式 - android

时间:2013-11-27 20:38:32

标签: java android json

我以json格式从API获取数据,使用此

public List<User> getUsers() throws IOException {
        try {
            HttpRequest request = execute(HttpRequest.get(SOME_URL));
            Reader reader = request.bufferedReader();
            Type type= new TypeToken<List<User>>() {}.getType();
            List<User> response = new GsonBuilder().create().fromJson(reader, type);
....

SOME_URL调用会返回此json

[{"id":1,"username":"some_username"}]并且效果很好。但是如果API返回此

[{"id":1,"username":"some_username","image":{"url":"/uploads/user/image/1/avatar.jpg"}}]

我收到此错误消息

DEBUG//ThrowableLoader.java:40(329): ModernAsyncTask #3 Exception loading data
        com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 282
        at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
        at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:81)
        at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:60)
        at com.google.gson.Gson.fromJson(Gson.java:803)
        at com.google.gson.Gson.fromJson(Gson.java:768)
        at com.donnfelker.android.bootstrap.core.BootstrapService.getUsers(BootstrapService.java:193)
        at com.donnfelker.android.bootstrap.ui.UserListFragment$1.loadData(UserListFragment.java:74)
        at com.donnfelker.android.bootstrap.ui.UserListFragment$1.loadData(UserListFragment.java:66)
        at com.donnfelker.android.bootstrap.ui.ThrowableLoader.loadInBackground(ThrowableLoader.java:38)
        at android.support.v4.content.AsyncTaskLoader.onLoadInBackground(AsyncTaskLoader.java:240)
        at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:51)
        at android.support.v4.content.AsyncTaskLoader$LoadTask.doInBackground(AsyncTaskLoader.java:40)
        at android.support.v4.content.ModernAsyncTask$2.call(ModernAsyncTask.java:123)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
        at java.util.concurrent.FutureTask.run(FutureTask.java:138)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
        at java.lang.Thread.run(Thread.java:1019)
        Caused by: java.lang.IllegalStateException: Expected a string but was BEGIN_OBJECT at line 1 column 282
        at com.google.gson.stream.JsonReader.nextString(JsonReader.java:821)

有人可以帮忙吗?

0 个答案:

没有答案