我正在使用 mongodb 作为我的 android 应用程序的云服务器。Mongodb java 库在 Android 中不起作用,所以我使用的是 rest api。我编写了以下代码来获取 json 响应并将它们转换为 MyClass 但它给出了 IllegalStateException
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_Object at line 1 column 35
代码 :
try { HttpGet mRequest = new HttpGet("https://api.mongolab.com/api/1/databases/mydb/collections/mycol?apiKey=myKey");
DefaultHttpClient client = new DefaultHttpClient();
try {
HttpResponse response = client.execute(mRequest);
InputStream source = response.getEntity().getContent();
Reader reader = new InputStreamReader(source);
Gson gson = new Gson();
Type typeOfCollectionOfMyObject = new TypeToken<Collection<MYObject>>(){}.getType();
quizDBObjectList = gson.fromJson(reader, typeOfCollectionOfMyObject);
} catch (IOException e) {
mRequest.abort();
}
这不是全部代码,但我在这个块中遇到了异常。有帮助吗?
MYObject 的定义是
public class MYObject {
private long index ;
private String question;
private String answer;
private String optionA;
private String optionB;
private String optionC;
private String optionD;
private String createdAt;
private String active;
//getters and setters of data members
}
我得到的回应是:
[ { "_id" : { "$oid" : "505ab996aded66f4c1ccc7f2"} , "index" : 0 , "question" : "some text ?" , "optiona" : "optionA" , "optionb" : "optionB" , "optionc" : "OptionC" , "optiond" : "optionD" , "answer" : "answer" , "created_at" : { "$date" : "2012-09-20T06:37:04.306Z"} , "Active" : "1"} , { "_id" : { "$oid" : "505ab997aded66f4c1ccc7f3"} , "index" : 1 , ..../objects like that]
显然我不知道服务器会响应 _id 的事实。你能给我正确的类定义来将此 json 对象转换为我的自定义类吗?谢谢