我正在使用mongodb作为我的Android应用程序的云服务器.Mongodb java库在Android中不起作用所以我使用rest api .i编写了以下代码来获取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对象强制转换为我的自定义类。感谢
答案 0 :(得分:1)
java.lang.IllegalStateException:预期BEGIN_ARRAY但在第1行第35列是BEGIN_Object
这说明了一切,应该有[
而不是{
。也许你得到一个对象而不是一个数组?
以上可能有所帮助。为了得到更好的答案,需要以下内容:
MYObject
您可以获取已解析的字符串,例如通过使用Guava的reader
从StringBuider
读取CharStreams.toString(reader)
或更简单。