i am using mongodb as cloud server for my android app.Mongodb java library doesn’t work in Android so i am using rest api .i wrote the following code to get the json response and cast them into MyClass but its giving IllegalStateException with
java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_Object at line 1 column 35
Code :
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();
}
this is not the whole code but i am getting the exception in this block.Any Help ?
Definition of MYObject is
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
}
and the response i got was :
[ { "_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]
clearly i was not aware of the fact that the _id would be responded by the server.
Can you give me the correct class definition to cast this json object into my customized class. thanks
This says it all, there should be somewhere
[instead of{. Maybe you get a single object instead of an array?The above might help or not. In order to get a better answer the following is needed:
MYObjectYou can get the parsed String e.g. by reading from
readerinto aStringBuideror simpler by using Guava’sCharStreams.toString(reader).