无法以正确的格式获取json对象

时间:2013-11-12 23:01:49

标签: java android json

假设我从某个json数组中取出api

[{"id":1,"title":"title","description":"description","vote":null,"created_at":"2013-11-12T21:08:10.922Z","updated_at":"2013-11-12T21:08:10.922Z"}]

我想从json url

中检索此Some URL_Some个对象
public class Some implements Serializable {

    private String id;
    private String title;
    private String description;
    private String vote;
    private String created_at;
    private String updated_at;
    }//with all getters and setters

public List<Some> getSome() throws IOException {
        try {
            HttpRequest request = execute(HttpRequest.get(URL_Some));
            SomeWrapper response = fromJson(request, SomeWrapper.class);
            Field[] fields = response.getClass().getDeclaredFields();
            for (int i=0; i<fields.length; i++)
            {
                try {
                    Log.i("TAG", (String) fields[i].get(response));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
                }
                Log.i("TAG", fields[i].getName());
            }
            if (response != null && response.results != null)
                return response.results;
            return Collections.emptyList();
        } catch (HttpRequestException e) {
            throw e.getCause();
        }
    }

SomeWrapper只是

private static class SomeWrapper {

        private List<Some> results;
    }

问题是我继续收到此消息

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

PS:我用

import com.google.gson.Gson;

import com.google.gson.GsonBuilder;

import com.google.gson.JsonParseException;

2 个答案:

答案 0 :(得分:1)

你的json应该是这样的:

{"results": [{"id":1,"title":"title","description":"description","vote":null,"created_at":"2013-11-12T21:08:10.922Z","updated_at":"2013-11-12T21:08:10.922Z"}]}

Gson将尝试解析json并创建一个SomeWrapper对象。仅此一个告诉Gson他将等待这种格式{...}的json,因为他期待一个对象。但是你传递了一个数组,这就是为什么它抱怨期望BEGIN_OBJECT({)而是获得BEGIN_ARRAY([)。之后,它会期望这个json对象有一个results字段,它将包含一个对象数组。

您可以直接创建List<Some>,而无需使用包装类。为此,请执行此操作:

Type type= new TypeToken<List<Some>>() {}.getType();
List<Some> someList = new GsonBuilder().create().fromJson(jsonArray, type);

在这种情况下,您可以使用您发布的原始json数组。

答案 1 :(得分:0)

您发布的JSON是一个JSON数组,由它周围的方括号表示:[]。

您必须从JSON数组中读取第一个对象。

我个人使用Android版JSON的org.json软件包,并以这样的方式解析我的JSON:

private void parseJSON(String jsonString) {
JSONArray json;
    try {
        json = new JSONArray(jsonString);
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        String id = jsonObject.getString("id");
    } catch (JSONException jsonex) {
        jsonex.printStackTrace();
    }
}

如果你的数组中有多个JSON对象,你可以使用一个简单的for循环来迭代它们(不是每个!)