0Solution 0Solution -4 years ago 199
Java Question

Parse and mongoDB json Object

I'm using the Parse API with mongoDB in my android application. In my database I have stored some values in a JSON Object like so :

"address": {
"state": "blabla",
"zipcode": 00000,
"lane": "blabla",
"city": "bla"
}


Saving works like a charm :

try{
JSONObject address = new JSONObject();
address.put("lane",mLane);
address.put("zipcode",mZipCode);
address.put("city",mCity);
address.put("state",mState);
user.put("address", address);
user.saveInBackground();
Toast.makeText(getContext(),"SAvedSuccessfully",Toast.LENGTH_SHORT).show();
} catch (JSONException j){
Toast.makeText(getContext(),"Error " +j,Toast.LENGTH_SHORT).show();
}


But I cannot figure out how to retrieve this data in my code. It always returns a null value. It works perfectly with other non JSON objects values.

JSONObject obj = new JSONObject();
obj = ParseUser.getCurrentUser.getJSONObject("address");


Here obj is null...

Any help would be appreciated !

Answer Source

look at this example.

ParseObject gameScore = new ParseObject("GameScore");
gameScore.put("score", 1337);
gameScore.put("playerName", "Sean Plott");

gameScore.put("cheatMode", false);
gameScore.saveInBackground()`;

I would use Gson convert to a string then store in parse.

Gson gson = new Gson();
String json = gson.toJson(address);
user.put("address",json);

now get the data.

Type type = new TypeToken<JSONObject>(){}.getType();
String json = ParseUser.getCurrentUser.getJSONObject("address");
JSONObject data = gson.fromJson(type,json);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download