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;
Related
I got this data in PayUMoney and to show the user But problem how to get this data in json or key value pair format any one know that please help!!
addedon=2019-11-21+17%3A06%3A42&productinfo=FINE&firstname=Creataum+Test+User&
Assuming that u have got it as String following code will print the key value pair from the string
String x ="addedon=2019-11-21+17%3A06%3A42&productinfo=FINE&firstname=Creataum+Test+User&";
String pair[] = x.split("&");
Log.e("pairs", Arrays.asList(pair).toString());
for (int i=0;i<pair.length;i++){
String key[] = pair[i].split("=");
Log.e("pair:","key= "+ key[0]+" value= "+key[1]);
}
It seems the string is both URL encoded (the %3A) and JSON encoded (the &).
You have to decode the string and then split by '&' and then split each pair to key and value by '='.
You can see here how to JSON decode: Decoding JSON String in Java
URL decoding can be done with Java's URLDecoder class: https://docs.oracle.com/javase/7/docs/api/java/net/URLDecoder.html
For this example I'll just assume the only encoded characters are %3A and &.
String payumoney = "addedon=2019-11-21+17%3A06%3A42&productinfo=FINE&firstname=Creataum+Test+User&";
// String decoding.
payumoney = payumoney.replaceAll("%3A", "-");
payumoney = payumoney.replaceAll("&", "&");
HashMap<String, String> params = new HashMap<String, String>();
String[] pairs = payumoney.split("&");
for (String pair : pairs) {
String[] keyValue = pair.split("=");
params.put(keyValue[0], keyValue[1]);
}
This looks like a String with mixture of URL encoding (like %3A for :) and HTML characters (like & for &).
I believe you can try decoding it and then split data like say by & to get data for each key and then further split by = to get value for that key.
For URL decoding you can try like
String decoded = java.net.URLDecoder.decode(url, "UTF-8");
You can simply use String replaceAll() function to create the json.
str= str.replaceAll("=", "\"");
str= str.replaceAll("&", "\",\"");
str= "{\""+ str+ "\"}";
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);
I am using the bulk sms api to trigger send an sms to mobile number in and android phone. The format of the bulk sms api is follows
http://xxx.xxx.xxx/bulksms/bulksms?username=fds-xxx&password=xxx&type=0&dlr=1&destination=9422522891,8275004333&source=xxx&message=18%20December
The following is the response I can get in android as string using code
bytesSent = httpclient.execute(httppost, res);
response below
1701|919422522891:224c1214-bb95-414d-ba76-77db95370545,1701|918275004333:5e93a439-2644-4455-9f01-f27e6cf0cde6
How do I parse this response like key value pairs ?
A little success with following code , but it fails when the regex char is '|'
public String[] split(String regex,String input)
{
input = "1701|919422522891:224c1214-bb95-414d-ba76-77db95370545,1701|918275004333:5e93a439-2644-4455-9f01-f27e6cf0cde6";
regex = "|"; // does not work
//regex = ":"; // works correct
String[] soso = Pattern.compile(regex).split(input, input.length());
for (String s : soso) {
Log.e("TAG",s.toString());
}
return null;
}
for regex char '|'
I get a Log output as single characters string array like {"1","7","0",........}
UPDATE
regex = "\\|" // works fine
Use the split() method of String to split the response into different entries.
Loop through the resulting array
use split() again to separate keys from values
store the result in a map, result[0] is the key,result[1] is the value
if you need to maintain order make sure you use a map that does that, e.g. LinkedHashMap
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 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;