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 !
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);
You can even: first change Parse to SharedPreferences
create Share
public void putUser (String key, String value ) {
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, value);
editor.commit();
}
next create JSONObject
JSONObject address = new JSONObject();
address.put("lane", "l");
address.put("zipcode", "z");
address.put("city", "c");
address.put("state", "s");
putUser("address", address.toString());
end get JSONObject
public String getUser (String key) {
SharedPreferences pref = getSharedPreferences("YourPref", MODE_PRIVATE);
return pref.getString(key, "");
}
JSONObject addressObject = new JSONObject(new String(getUser("address")));
if(addressObject != null) {
addressObject.getString("lane");
addressObject.getString("zipcode");
addressObject.getString("city");
addressObject.getString("state");
}
Okey I figured it out thanks to #Caspain ! To save the data to the DB use :
ParseUser user = ParseUser.getCurrentUser();
JSONObject address = new JSONObject();
Gson gson = new Gson();
try{
address.put("lane",mLane);
address.put("zipcode",mZipCode);
address.put("city",mCity);
address.put("state",mState);
} catch (JSONException j){
Log.i("TEST",j.toString());
}
String json = gson.toJson(address);
user.put("address", json);
user.saveInBackground();
And to retrieve the data :
String json = ParseUser.getCurrentUser().getJSONObject("address").toString();
try{
JSONObject data = new JSONObject(json);
String lane = data.getString("lane"); // do whatever with your JSON Object
}catch (JSONException j){
Log.i("Erreur",j.toString());
}
Related
I'm new to TypeTokens and I'm having a problem. I have a shopping cart with products, and
those products I save to Shared Preferences using Typetoken. Because I need to delete and
remove products from recyclerview. Here what I have for adding products:
Gson gson = new Gson();
String json = preferences.getString("artikujtShporta", "");
ArrayList<Artikujt> artikullObject = gson
.fromJson(json, new TypeToken<ArrayList<Artikujt>>(){}.getType());
if (artikullObject != null) {
artikullObject.add(mArtikull);
String jsonString = gson.toJson(artikullObject);
mEditor.putString("artikujtShporta", jsonString);
mEditor.apply();
} else {
ArrayList<Artikujt> arrayArtikuj = new ArrayList<>();
arrayArtikuj.add(mArtikull);
Type listOfTestObject = new TypeToken<ArrayList<Artikujt>>() {}.getType();
String s = gson.toJson(arrayArtikuj, listOfTestObject);
mEditor.putString("artikujtShporta", s);
mEditor.apply();
}
Now I need to send this object to server with some additional information, as below:
private void sendBasketItemsToServer() {
//service where retrofit instance is defined for current route
ProductsService prodService = new ProductsService();
// Retrieve the product of the shopping cart which are saved in shred preferences
SharedPreferences preferences = getSharedPreferences(ITEMS_PREF, Context.MODE_PRIVATE);
SharedPreferences.Editor my_editor = preferences.edit();
String json = preferences.getString("artikujtShporta", "");
Gson gson = new Gson();
ArrayList<Artikujt> artikujt = gson
.fromJson(json, new TypeToken<ArrayList<Artikujt>>(){}.getType());
final int order_number = new Random().nextInt(26) + 75;
String date = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
// initialize requestBody
RequestBody requestBody = null;
try {
JSONObject jsonObject = new JSONObject();
jsonObject.put("klienti", full_name);
jsonObject.put("adresa", fullAddress);
jsonObject.put("produktet", artikujt);
jsonObject.put("date", date);
jsonObject.put("order_number", String.valueOf(order_number));
requestBody = RequestBody.create(String.valueOf(jsonObject),
MediaType.parse("application/json; charset=utf-8"));
System.out.println(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
}
// Get token, stored in shared preferences
SharedPreferences editor = Objects.requireNonNull(getApplicationContext())
.getSharedPreferences(TOKEN_PREF, MODE_PRIVATE);
String token = editor.getString("token", "");
Callback<BasketResponse> callback = new Callback<BasketResponse>() {
#Override
public void onResponse(#NotNull Call<BasketResponse> call, Response<BasketResponse> response) {
if (response.isSuccessful()) {
// clear products added to cart
my_editor.clear();
my_editor.apply();
System.out.println(response.body());
Intent intent = new Intent(CheckoutActivity.this, SuccessOrderActivity.class);
startActivity(intent);
}
}
#Override
public void onFailure(#NotNull Call<BasketResponse> call, Throwable t) {
Toast.makeText(CheckoutActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
};
prodService.sendBasketItemsToServer(callback, token, requestBody);
}
All of the items are sent to server and I'm receiving a code 200 as response, but I have a
problem with products, with this line:
jsonObject.put("produktet", artikujt);
is displayed like this:
Is sending the name of the class, not products. When I debug in Android Studio, everything
seems okay
I have two days figuring out how to solve this, but I don't know how. Can someone have any
suggestion what I'm missing here or what I'm doing wrong. Thanks in advance.
Edit: I want to send to server a json like below:
{
"klienti": "my name",
"address": "my address",
"products": [
{
"id": 1,
"price": 2234,
"category": 3,
"created_at": 23-03-2020
},
{
"id": 2,
"price": 2534,
"category": 3,
"created_at": 23-03-2020
}
],
"date": 03-09-2020,
"order_number": 93
}
jsonObject.put("produktet", artikujt);
This line is simply adding the java object to jsonObject.
You can instead do
jsonObject.put("produktet", new Gson().toJson(artikujt));
Edit:
If you are using org.json.JSONObject, try
JSONArray jsonArray = new JSONArray();
artikujt.forEach(item -> {
jsonArray.put(new JSONObject(item));
});
jsonObject.put("produktet", jsonArray);
Though better solution would be to create a java class denoting your target json.
class ArtikujtData {
private String klienti;
private String address;
private List<Artikujt> products;
private String date;
#SerializedName(value = "order_number")
private String orderNumber;
// setters and getters
}
Create object of ArtikujtData and set values to it and use it as
requestBody = RequestBody.create(new Gson().toJson(artikujtData),MediaType.parse("application/json; charset=utf-8"));
I have a json as below. I want to get mobile_number from this jsonObject.
json:-
{"id": "ABCD", "report": { "data": { "phone": { "mobile_number": 9876543210, "active": "Y", "content": null } } } }
I am doing it like this and it works fine but can someone help me with any other approach for it without getting every key.
JSONObject jsonObject = new JSONObject(json);
JSONObject report = getJSONObjectFromJson(jsonObject, "report");
JSONObject data = getJSONObjectFromJson(jsonObject, "data");
JSONObject phone = getJSONObjectFromJson(data, "phone");
long mobileNumber = getLongFromJson(phone, "mobile_number");
private Long getLongFromJson(JSONObject object, String key){
return (object !=null && object.has(key)) ? object.getLong(key) : null;
}
private JSONObject getJSONObjectFromJson(JSONObject object, String key){
return (object !=null && object.has(key)) ? object.getJSONObject(key) : null;
}
I've just dealing with the similar issue and decided to use JsonPath like this:
final DocumentContext jsonContext = JsonPath.parse(jsonString);
final Object read = jsonContext.read("$['report']['data']['phone']['mobile_number']");
You can use Jackson ObjectMapper.
try {
ObjectMapper mapper = new ObjectMapper();
String jsonString = "{\"id\": \"ABCD\", \"report\": { \"data\": { \"phone\": { \"mobile_number\": 9876543210, \"active\": \"Y\", \"content\": null } } } }";
JsonNode rootNode = mapper.readTree(jsonString);
JsonNode mobileNumber = rootNode.path("report").path("data").path("phone").path("mobile_number");
System.out.println("Mobile Number: " + mobileNumber.longValue());
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
So there are lot of ways to do it but everything leads eventually to traversing the tree.
So to conclude all the approaches,
1. **Convert string to JsonObject and traverse.**
JSONObject jsonObject = new JSONObject(json);
JSONObject report = getJSONObjectFromJson(jsonObject, "report");
JSONObject data = getJSONObjectFromJson(jsonObject, "data");
JSONObject phone = getJSONObjectFromJson(data, "phone");
long mobileNumber = getLongFromJson(phone, "mobile_number");
private Long getLongFromJson(JSONObject object, String key){
return (object !=null && object.has(key)) ? object.getLong(key) : null;
}
private JSONObject getJSONObjectFromJson(JSONObject object, String key){
return (object !=null && object.has(key)) ? object.getJSONObject(key) : null;
}
2. **Using jackson objectMapper to get the JsonNode and then traverse.**
ObjectMapper mapper = new ObjectMapper();
JsonNode jsonNode= mapper.readTree(json);
JsonNode mobileNumber = jsonNode.path("report").path("data").path("phone").path("mobile_number");
3. **Using gson jsonmapper to convert to map and then iterate the map.**
Gson gson = new Gson();
Map map = gson.fromJson(json, Map.class);
jsonObject.getJSONObject("x").getJSONObject("Y").getJSONObject("z");
Another route would be to leverage the ObjectMapper.
in my application data coming from a server in the form of an array,
i cant handle the data i will share my code please help me.
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(),"inside",Toast.LENGTH_LONG).show();
try {
JSONArray array = jsonObject.getJSONArray("data");
for (int i = 0; i < array.length(); i++) {
jsonObject = array.getJSONObject(i);
s_key = jsonObject.getString("initKey");
s_iv = jsonObject.getString("initIv");
sec_url = jsonObject.getString("url");
s_init_hash = jsonObject.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}
There is no JSONArray
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(),"inside",Toast.LENGTH_LONG).show();
try {
JSONObject jsonObjectData = jsonObject .getJSONObject(i);
s_key = jsonObjectData.getString("initKey");
s_iv = jsonObjectData.getString("initIv");
sec_url = jsonObjectData.getString("url");
s_init_hash = jsonObjectData.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}
You Response is JSONObject not in JSONArray check it
FYI
{ } brackets means JSONObject
[ ] brackets means JSONArray
Parse your json like this
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(), "inside", Toast.LENGTH_LONG).show();
try {
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
s_key = data.getString("initKey");
s_iv = data.getString("initIv");
sec_url = data.getString("url");
s_init_hash = data.getString("initHash");
} catch (JSONException e) {
e.printStackTrace();
}
}
data Is not Json Array cause it start with {} it`s Json Object
Json Array start with []
So you need To use
SONObject jsonObjectData = jsonObject .getJSONObject(i);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
JSONObject jsonObjectData = jsonObject.getJSONObject("data");
s_key = jsonObjectData.getString("initKey");
s_iv = jsonObjectData.getString("initIv");
sec_url = jsonObjectData.getString("url");
s_init_hash = jsonObjectData.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}
response
{
"status": "success",
"data": {
"initKey": "abc",
"initHash": "cde",
"initIv": "efg",
"versionNo": "123 ",
"url": "https://www.youtube.com"
}
}
Code
try {
JSONObject outerJsonObject=new JSONObject(response);
String status=outerJsonObject.getString("status");
if(status.equals("success"))
{
JSONObject innerJsonObjectData=outerJsonObject.getJSONObject("data");
String initKey =innerJsonObjectData.getString("initKey");
String initHash =innerJsonObjectData.getString("initHash");
String initIv =innerJsonObjectData.getString("initIv");
String versionNo =innerJsonObjectData.getString("versionNo");
}
} catch (JSONException e) {
e.printStackTrace();
}
Comments
/*
{
//outerJsonObject
"status":"success",
"data": // innerJsonObjectData
{
"initKey":"abc",
"initHash": "cde",
"initIv": "efg",
"versionNo": "123 ",
"url": "https://www.youtube.com"
}
}
*/
When you are working with JSON data in Android, you would use JSONArray to parse JSON which starts with the array brackets. Arrays in JSON are used to organize a collection of related items (Which could be JSON objects).
For example:
[{"name":"item 1"},{"name": "item2} ]
On the other hand, you would use JSONObject when dealing with JSON that begins with curly braces. A JSON object is typically used to contain key/value pairs related to one item. For example:
{"name": "item1", "description":"a JSON object"}
JSONObject jsonObject = new JSONObject(response);
String name = jsonObject.getString("status");
String name1 = name.trim();
if (name1.equals("success")) {
Toast.makeText(getApplicationContext(),"inside",Toast.LENGTH_LONG).show();
try {
JSONObject data = jsonObject. getJSONObject("data");
s_key = data.getString("initKey");
s_iv = data.getString("initIv");
sec_url = data.getString("url");
s_init_hash = data.getString("initHash");
}
} catch (JSONException e) {
e.printStackTrace();
}
How to create a JSON object, in Android using java code.
{
"apikey": "example apikey",
"id": "example id",
"email": {
"email": "example email",
"euid": "example euid",
"leid": "example leid"
}
}
You can create json you mentioned in question as below :
public void createJson() {
try {
// create outer json
JSONObject jsonObject = new JSONObject();
jsonObject.put("apikey", "example api key");
jsonObject.put("id", "example id");
// create email json
JSONObject emailJsonObject = new JSONObject();
emailJsonObject.put("email", "email");
emailJsonObject.put("euid", "euid");
emailJsonObject.put("leid", "leid");
// add email json to outer json
jsonObject.put("email", emailJsonObject);
System.out.println("-----printing json------" + jsonObject.toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
Thanks..!!
you can do like this:
JSONObject jsonObject = new JSONObject();
jsonObject.put("apikey","example apikey");
jsonObject.put("id","example id");
JSONObject innerObject = new JSONObject();
innerObject.put("email","example email");
....
jsonObject.put("email",innerObject);
and to convert to String you can do like jsonObject.toString();
Do like thist.
JSONObject myJson = new JSONObject();
myJson.put("apikey","example apikey");
myJson.put("id","example id");
JSONObject emailObject = new JSONObject();
emailObject.put("email","example email");
emailObject.put("euid","example euid");
emailObject.put("leid","example leid");
myJson.put("email",emailObject);
Create a class with the constructor you want.
Likes:
class MyJsonObj{
public string apikey;
public string id;
public string[] email;
}
Then instance the class
MyJsonObj myObj = new MyJsonObj();
myObj.apikey = "testKey";
myObj.id = "0123";
myObj.email = new string[]{"01#gamil.com","02#gmail.com"};
Last, convert to json string by Gson library
Gson gson = new Gson();
String json = gson.toJson(myObj);
I would like to append JSON object to existing JSON array to get data structure like this.
"results":[
{
"lat":"value",
"lon":"value"
},
{
"lat":"value",
"lon":"value"
}
]
I'm trying to do it using the code in example, but unfortunately whole object is overriden everytime.
Log.i(AppHelper.APP_LOG_NAMESPACE, "POSITIONS AVAILABLE " + jsonDataString);
AppHelper helper = new AppHelper(ctx);
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
//putv given values to the JSON
valuesObject.put("lat", lat.toString());
valuesObject.put("lon", lon.toString());
valuesObject.put("city", city);
valuesObject.put("street", street);
valuesObject.put("date", helper.getActualDateTime());
valuesObject.put("time", helper.getActualDateTime());
list.put(valuesObject);
//mainObject.put("values", list);
mainObject.accumulate("values", list);
saveJsonData(ctx, mainObject.toString(),"positions");
How it should be right?
Put and accumulate everytime rewrite all previous values, but i would like to append this object:
{
"lat":"value",
"lon":"value"
},
Into results parent.
BTW: I would like to do it without GSON.
Thanks for any help..
There isnt any problem with your code. It does append
String jsonDataString = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
JSONObject mainObject = new JSONObject(jsonDataString);
JSONObject valuesObject = new JSONObject();
JSONArray list = new JSONArray();
valuesObject.put("lat", "newValue");
valuesObject.put("lon", "newValue");
valuesObject.put("city", "newValue");
valuesObject.put("street", "newValue");
valuesObject.put("date", "newValue");
valuesObject.put("time", "newValue");
list.put(valuesObject);
mainObject.accumulate("values", list);
System.out.println(mainObject);
This prints {"values":[[{"date":"newValue","city":"newValue","street":"newValue","lon":"newValue","time":"newValue","lat":"newValue"}]],"results":[{"lon":"value","lat":"value"},{"lon":"value","lat":"value"}]}.
Isnt this what you are expecting?
With gson you can do like
import com.google.gson.Gson;
import com.google.gson.JsonObject;
public class AddJson {
public static void main(String[] args) {
String json = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }, { \"lat\":\"value\", \"lon\":\"value\"}]}";
Gson gson = new Gson();
JsonObject inputObj = gson.fromJson(json, JsonObject.class);
JsonObject newObject = new JsonObject() ;
newObject.addProperty("lat", "newValue");
newObject.addProperty("lon", "newValue");
inputObj.get("results").getAsJsonArray().add(newObject);
System.out.println(inputObj);
}
}
Simple Approach
String jsonData = "{\"results\":[{\"lat\":\"value\",\"lon\":\"value\" }]}";
System.out.println(jsonData);
try {
JSONArray result = new JSONObject(jsonData).getJSONArray("results");
result.getJSONObject(0).put("city","Singapore");
jsonData = "{\"results\":"+result.toString()+"}";
System.out.println(jsonData);
} catch (JSONException e) {
e.printStackTrace();
}
OutPut Before Appending
{"results":[{"lat":"value","lon":"value" }]}
OutPut After Appending
{"results":[{"lon":"value","lat":"value","city":"Singapore"}]}
If you want to add new value to an Object you can try the below as well
Before:
{
"Name": "EnCoMa",
"Manager": "Abhishek Kasetty"
}
code :
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
String json = ow.writeValueAsString(TheObjectToWhichYouWantToAddNewValue);
ObjectNode node = (ObjectNode) mapper.readTree(json);
node.putPOJO("new Key","new value")
after:
{
"Name": "EnCoMa",
"Manager": "Abhishek Kasetty",
"new Key": "new value"
}