Android Gson - deserializing null vs absent values - android

I'd like to understand the difference with a server returning value verses that value being completely absent in the response.
lets take at what i have so far:
data class MyApiResponse(#SerializedName("name") val name: String,
#SerializedName("address") val address: String,
#SerializedName("max_time") val maxTime: Double? = null //this field might BE COMPLETELY absent in response, what will happen here ?
)
regarding the maxTime value, if the value is COMPLETELY absent from server response, will the app crash or will the value be null ?
the issue is im trying to distinguish between server sending
max_time: null vs it being completely absent ,how does gson handle this ?

In both cases it will be null.
Might look here for more info:
Gson optional and required fields

Please try this solution:
String json = ""; //Your json has a String
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
String name = jsonObject.get("name").toString();
String adress = jsonObject.get("address").toString();
//If null, use a default value
JsonElement max_time = jsonObject.get("max_time");
String text = (max_time instanceof JsonNull) ? "" : max_time.getAsString();
String json = ""; //Your json has a String
Gson gson = new GsonBuilder().serializeNulls().create();
MyApiResponse myApiResponse = gson.fromJson(json, YOURCLASSNAME.class);

Related

Value of type java.lang.String cannot be converted to JSONObject - Android

Seen this thread for possible solutions but it beats me.
I store a customer data object as a JSON String in shared preferences (Android) and try to retrieve the string convert back to customer object and use for validations. The conversion from object to JSON String occurs perfectly well and stores in preferences (as a key value(string) pair).
When I try to create a JSONObject or an array (Its not an array but tried anyway) using the SharedPreferences.getString(key,"") - I always get the same error "Value ... of type java.lang.String cannot be converted to JSONObject".
I am hoping a different pair of eyes catch something I could not.
Error message with data (masked):
Value
{"address":{"city":"city","country":"country","customer_address_id":0,"customer_id":0,"house_number":"#123, Lane 1, Street 1","latitude":0.0,"longitude":0.0,"postcode":"12001","street":"Lane 2, Street 2"},"ageGroup":"25-45","dateOfBirth":"1537308474000","email":"abc#abc.com","firstName":"abcdefg","gender":"","id":"108","lastName":"xyz","locale":"en_us","middleName":"none","phone":"1234567890","uuid":"8c3ce2c5-600f-3c4e-bc07-727d61fae7ff"}
of type java.lang.String cannot be converted to JSONObject.
All am trying to do is (gist of code):
Saving to shared prefs using below:
jsonAdapter = moshi.adapter(RegisterUser.class);
mRegisterUser = (RegisterUser) jsonAdapter.fromJson(regisCustUser.toString());
prefs = UserPrefs.getUserPrefs(getApplicationContext());
prefs.setPrefsItem(UserPrefs.getregUserKey(), jsonAdapter.toJson(mRegisterUser));`
where setPrefsItem does below:
JsonAdapter jsonAdapter = moshi.adapter(javaObject.getClass());
String cartJson = jsonAdapter.toJson(javaObject);
// Log.e("CartJsonreflection", cartJson);
editor.putString(prefKey, cartJson);
editor.commit();
Here is where retrieve occurs:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
...
private static SharedPreferences settings;
...
public static Object someMethod(String prefKey, Object javaObject) {
String prefJson = settings.getString(prefKey, "");
JSONObject regisCustomer = new JSONObject(prefJson);
javaObject = (someObject) jsonAdapter.fromJson(regisCustomer.toString());
// casting is redundant but added for clarity
return javaObject;
}
Where prefJson has the above string.
I have tried to validate the JSON string on two websites - https://jsoneditoronline.org/ and https://jsonlint.com/
I have even pasted the string in Notepad++ for any special characters but found none.
Might be the case that you are trying to convert the empty string which the default string to JSONObject .
Make sure you are getting a value in prefJson by , making sure that you have initialized the SharedPreferenceswith the correct key and the key for the getString() is also right.
var s ="{\"address\":{\"city\":\"city\",\"country\":\"country\",\"customer_address_id\":0,\"customer_id\":0,\"house_number\":\"#123, Lane 1, Street 1\",\"latitude\":0.0,\"longitude\":0.0,\"postcode\":\"12001\",\"street\":\"Lane 2, Street 2\"},\"ageGroup\":\"25-45\",\"dateOfBirth\":\"1537308474000\",\"email\":\"abc#abc.com\",\"firstName\":\"abcdefg\",\"gender\":\"\",\"id\":\"108\",\"lastName\":\"xyz\",\"locale\":\"en_us\",\"middleName\":\"none\",\"phone\":\"1234567890\",\"uuid\":\"8c3ce2c5-600f-3c4e-bc07-727d61fae7ff\"}";
val regisCustomer = JSONObject(s)
println(regisCustomer.toString())
Since hardcoding the string with your value worked .
Try below
Gson gson = new GsonBuilder().create();
public static <T> T someMethod(String prefKey, Class<T> type) {
String prefJson = settings.getString(prefKey, "");
return gson.fromJson(prefJson , type);
}
Solution includes pieces of answers from other post.
I had to do:
prefJson= prefJson.replace("\\\"", "\"");
prefJson = prefJson.substring(prefJson.indexOf("{"), prefJson.lastIndexOf("}") + 1);
The quirky thing was the sharedpreferences had the exact string as below (including start and end quotes('"') in the value. Not sure why that was an issue, only when passed as a parameter. The quotes and the escape characters were ignored when hard coded into the string variable:
"{\"address\":{\"city\":\"City\",\"country\":\"Country\",\"customer_address_id\":0,\"customer_id\":0,\"house_number\":\"#123, Lane 1, Street 1\",\"latitude\":0.0,\"longitude\":0.0,\"postcode\":\"PA 12345\",\"street\":\"Lane 2, Street 2\"},\"ageGroup\":\"25-45\",\"dateOfBirth\":\"1537368909000\",\"email\":\"abc#abc.com\",\"firstName\":\"First Name\",\"gender\":\"\",\"id\":\"119\",\"lastName\":\"Last Name\",\"locale\":\"en_us\",\"middleName\":\"none\",\"phone\":\"0987654321\",\"uuid\":\"8c3ce2c5-600f-3c4e-bc07-727d61fae7ff\"}"
which had to be converted to:
{"address":{"city":"City","country":"Country","customer_address_id":0,"customer_id":0,"house_number":"#123, Lane 1, Street 1","latitude":0.0,"longitude":0.0,"postcode":"PA 12345","street":"Lane 2, Street 2"},"ageGroup":"25-45","dateOfBirth":"1537368909000","email":"abc#abc.com","firstName":"First Name","gender":"","id":"119","lastName":"Last Name","locale":"en_us","middleName":"none","phone":"0987654321","uuid":"8c3ce2c5-600f-3c4e-bc07-727d61fae7ff"}
Note: Moderators, please feel free to remove or merge this questiont if this sounds repetitive.Thank you everyone.

How to Split response from Json in android?

I am developing an app in which I got response like "100.0" from server which I have to split to "100" and save in variable.How can I do that kindly tell me .
You can use this code to parse your JSON response. Store your wallet balance in a String, them trim the value as per your request
JSONObject object = new JSONObject(JsonResponseText);
String walletBal = object.getString("wallet balance");
String trimWalletBal = walletBal.subString(0,walletBal.indexOf('.'));
You can do it this way:
Integer value = jsonObject.getDouble("parameter").intValue();
Assuming that your problem is just to split the "Integer" and "Fraction" part of a "string" value you are getting from the server -
int decimalIdx = stringVal.indexOf('.');
if (decIdx != -1) {
return stringVal.substring(0, decIdx);
}
return stringVal;

Gson. converting to JSON a password with the character =

I'm using Gson in an Android app to convert a complicated object to JSON representation. One of the fields is a string called QuickPin containing an encrypted password and the character "=" is converted to "\003d" by Gson.
The Json string is consumed by a C# WEBAPI application, but returns "an error has occurred" message.
The following JSON returns that error message :
{"UserContractID":"929c1399-11c4-490e-8cff-5b1458ac18e2","UserAuthentication":"MethodCombo":{"AuthMethod":[1]},"QuickPin":"mW2n2uTECEtVqWA2B9MzvQ\u003d\u003d"},"CustomerID":0,"OriginID":0,"OriginTypeID":0,"Status":0}
Meanwhile this JSON works fine :
{"UserContractID":"929c1399-11c4-490e-8cff-5b1458ac18e2","UserAuthentication":{"QuickPin":"mW2n2uTECEtVqWA2B9MzvQ==","MethodCombo":{"AuthMethod":[1]}},"CustomerID":0,"OriginID":0,"OriginTypeID":0,"Status":0}
Are there a way to force Gson to maintain the string with the password with the = (and others if is the case) characters?
My Android code is :
Gson gson = new Gson();
user = new User();
user.UserAuthentication = new UserAuthentication();
user.UserAuthentication.QuickPin = "mW2n2uTECEtVqWA2B9MzvQ==";
user.UserAuthentication.MethodCombo = new MethodCombo();
user.UserAuthentication.MethodCombo.AuthMethod = new ArrayList<Integer>();
user.UserAuthentication.MethodCombo.AuthMethod.add(1);
user.Status = 0;
String jsonRepresentation = gson.toJson(user);
object.put("user", jsonRepresentation);
Thanks
Gson escapes HTML metacharacters by default. You can disable this behavior.
Gson gson = new GsonBuilder().disableHtmlEscaping().create();

How is this JSON string supposed to be parsed to get the different fields

I have this JSON string that I am recieving after I make a purchase from the playstore and I am apparently missing something in my code when I am trying to parse it.
PurchaseInfo:{"orderId":"12999763165555505758.1317333586444405",
"packageName":"com.mypkgname.myapp",
"productId":"monthly_purchase_01",
"purchaseTime":1357456489000,
"purchaseState":0,
"purchaseToken":"yrynypfkdncvhlxdbypysvwz.AO-J1OxFkndfqkClAqbbYAOApkMgTG4VX9Ef0uNP0FIs9-xGrXivkbx3FNMA2yNU12K_sbvRGFcknVBTfisI-uZawCXLGlMX4v4Zw8GFOmS0Q6PIbiITTGqn5h1QbEB4Rv84sXdUJHP3B_UQfujZN7ADi9bm_N4_iA"}
Here is the snippet of code I am using it to attempt the parsing
try {
JSONObject j1 = new JSONObject(tester1);
JSONArray mPurchInfo = j1.getJSONArray("PurchaseInfo");
int count = mPurchInfo.length();
final String[] purchInfo = new String[count];
JSONObject q1 = mPurchInfo.getJSONObject(0);
purchInfo[0] = q1.getString("orderId");
purchInfo[1] = q1.getString("packageName");
purchInfo[2] = q1.getString("productId");
purchInfo[3] = q1.getString("purchaseTime");
purchInfo[4] = q1.getString("purchaseState");
purchInfo[5] = q1.getString("purchaseToken");
orderID=purchInfo[0];
} catch (JSONException e) {
Log.e("Error","Yes");
}
I am catching the an error as I see this last log statement in my log but I am still trying to learn the parsing JSON Strings
I hope I am at least close
Ideally I would like to have Strings set to all the values in the JSON String
orderID = ??
packageName = ??
etc.
Thanks
I have this JSON string that I am recieving after I make a purchase from the playstore
If that's really what you get back, you need to contact them and tell them to fix their API; that string is not valid JSON. There are two problems with it:
A JSON document must have an object or array as the top-level item. The string as quoted is missing a { at the beginning and a } at the end.
All keys in JSON must be in double quotes. The first one, PurchaseInfo, is not.
Also, your code is doing this:
JSONArray mPurchInfo = j1.getJSONArray("PurchaseInfo");
...but if it were valid JSON, PurchaseInfo wouldn't be an array, it'd be an object.
Looking at it, if you remove the PurchaseInfo: at the beginning, it's valid. Once you've removed that, this line:
JSONObject j1 = new JSONObject(tester1);
...will give you an object from which you can query information:
String orderId = j1.getString("orderId");

Not able to get name/value pairs from JSON object, when using variable

Not able to get name/value pairs from JSON object, when using the variable but able to read it when hard coding the name.
To better explain :
1) My JSON object is like this -
{.....
{ "rates":{ "name1": value1, "name2": value2 ...etc }
...}
2) I am able to read this object in my android app.
3) Now this rate object name value pairs, i am trying to read based on user input -
String s1 = '"'+name1+'"'; // here name1 i got from user input, & converted into string
4) Now when i am trying to get the value from rates object, i am getting null exception -
JSONObject rateObject = jObject.getJSONObject("rates"); //able to get
complete object
String rate1 = (String) rateObject.get(s1); // giving NULL exception
5) But if i use hard code string, it works -
String rate1 = (String) rateObject.get("name1"); // working
Any pointers why its not working while using variable.
thanks
Thanks for suggestions, i sorted out the problem. There are 2 mistakes i was doing - 1) Using the quotes as correctly pointed out by others and 2) casting the double value to string. Correcting both has resolved my problem :)
In terms of your final code snippet, you are actually doing
String rate1 = (String) rateObject.get("\"name1\""); //note the extra quotes
because you have bookended the user input string with double-quote characters. You just want the input string itself with no bookending. The quotes in the JSON notation serve to delineate each key name; the quotes are not part of the key name itself.
You need to omit the quotes when you create s1:
String s1 = name1;
Or, if name1 is not a String already:
String s1 = name1.toString();
Replace:
String s1 = '"'+name1+'"';
with:
String s1 = name1;

Categories

Resources