pass string as a variable in json key value pair - java

I am trying to pass the value of the dummy into the id but the syntax is not proper.
String dummy = getSysCodeOfAccount(X_Table, "delivery");
String jsonRollups = [{"id":dummy},{"percentage":"100.000000"}];

This is the correct json string:
String dummy="sample";
String jsonRollups = "{\"id\":\""+dummy+"\",\"percentage\":\"100.000000\"}";

Related

Extracting value dynamically from key==value set from a Decoded URL String, given a key

I have a Decoded URL String that is created dynamically that is in the following form.
field1==Z;field2==abc;field3==000;field4==100000154;field5==XLPO;field6==Z3&limit=2
I want to be able to dynamically pass in a key and obtain its relavent value. Say if we pass in "field2" then we should get "abc".
Example:
public class ComplexQueryParamProcessor {
public static void main(String[] args) {
String URL = "field1==Z;field2==abc;field3==000;field4==100000154;field5==XLPO;field6==Z3&limit=2";
String value = getValueFromURLString(URL, "field4"); // should return "100000154"
System.out.println(value);
}
public static String getValueFromURLString (String URL, String key){
String value = null;
//do something and extract "value" of "key" from URL
return value;
}
}
Any help would be greatly appreciated.
Thanks to schred I was able to figure it out using a combination of indexOf() and split()
public static String getValueFromURLString (String URL, String key){
String value = null;
//do something and extract "value" of "key" from URL
int index = URL.indexOf(key);
String s1 = URL.substring(index, URL.length());
String s2 = s1.split(";" , 2)[0];
value = s2.split("==", 2)[1];
return value;
}

Parsing map JSON value and reinserting back into map

I am trying to parse a map and update the value in it...
Here is the content of the .txt file that I have made the hashmap
The first line is the key and the JSON string is the value.
Not_enough_parameters
{"status": false, "errorMessage": "Payload has incorrect amount of parts: expecting: 18, actual:8", "version": "0.97", "coreName": "Patient_Responsibility"}
Here is my parsing code:
parse = params.split("\\|");
String key;
String value;
String value2;
String key2;
String value3;
Map<String, String> predictionFeatureMap = mockconfig.getPredictionFeatureMap();
if(parse.length!=18) {
key = "Not_enough_parameters";
value = predictionFeatureMap.get(key);
Map<?,?> resultJsonObj = new Gson().fromJson(value, Map.class);
key2 = "errorMessage";
value2 = (String) resultJsonObj.get(key2);
value3 = value2.substring(0,61) +parse.length+value2.substring(62);
}
I am sending a payload string named params that is separated by "|" separators. They input must have 18 parameters(18 values in-between the "|" separators). I parse the input and if it does not have enough parameters I get they key containing the string "Not_enough_paramters" and then get its value which is the JSON string.
I then take that JSON string and using Gson create a map out of it.
I did that because I want value to return
{"status": false, "errorMessage": "Payload has incorrect amount of parts: expecting: 18, actual:(params.length)", "version": "0.97", "coreName": "Patient_Responsibility"}
So I want "actual:" to be updated. I get the value from the JSON map for "errorMessage" and using substring I get the index and change the value to update the actual amount of parameters the user put in.
I am not sure how to reinsert the new JSON into the entire JSON string in the JSON map and then into the original map.
So I implemented a solution although I am not sure it is the cleanest and most straight forward.
I still got the substring from the value from the "errorMessage" key in the JSON Map.
I then replaced the value of that key with the new edited JSON.
Then I took the Json Map and converted it into a string.
I then added the new JSON string to the value of the original hashmap
String[] parse;
#PostMapping(value = "/")
public String payloader(#RequestBody String params ) throws IOException{
LOGGER.debug("code is hitting");
String key,key2;
String value,value2,value3;
Map<String, String> predictionFeatureMap = mockconfig.getPredictionFeatureMap();
if(parse.length!=18) {
key = "Not_enough_parameters";
value = predictionFeatureMap.get(key);
Map<String,Object> resultJsonObj = new Gson().fromJson(value, Map.class);
key2 = "errorMessage";
value2 = (String) resultJsonObj.get(key2);
value3 = value2.substring(0,61) +parse.length+value2.substring(62);
resultJsonObj.replace(key2, value3);
String updatedResponse = new Gson().toJson(resultJsonObj,Map.class);
value = updatedResponse;
}
else {
key = params;
value = predictionFeatureMap.get(key);
}
return value;

Retrieve hashmap data SharedPreferences

I used HashMap to store data which I received using API. After that, I used SharedPreferences to store the received HashMap data. Storing part is done. I can see the number of records which I wanted to store using SharedPreferences.
Here is the code to save data:
if (result != null && result.length() > 0)
{
for (int j = 0; j < result.length(); j++)
{
JSONObject resultObj = result.getJSONObject(j);
String label_id = resultObj.getString("label_id");
String arabic = resultObj.getString("arabic");
String english = resultObj.getString("english");
String key = resultObj.getString("key");
//Create a new model and set the received value
LabelModel labelModel = new LabelModel();
labelModel.setLabelId(label_id);
labelModel.setArabic(arabic);
labelModel.setEnglish(english);
labelModel.setKey(key);
int label = Integer.parseInt(label_id);
//Put the value
map.put(label, labelModel);
}
}
//With the below line, I stored the hashMap data using SharedPreferences
Pref.setValue(mActivity, AppPrefrences.PREF_LABELS, map);
After the above steps, I followed this set of code to set and get the value from SharePreferences, which I stored in application using SharedPreferences.
For that, I used this below code:
public static String PREF_LABELS ="labels";
public static void setValue(#NonNull Context context, String key, Object obj) {
Pref.openPref(context);
Editor prefsPrivateEditor = Pref.sharedPreferences.edit();
prefsPrivateEditor.putString(key, String.valueOf(obj));
prefsPrivateEditor.commit();
prefsPrivateEditor = null;
Pref.sharedPreferences = null;
}
#Nullable
public static String getValue(#NonNull Context context, String key, Object obj) {
Pref.openPref(context);
String result = Pref.sharedPreferences.getString(key, String.valueOf(obj));
Pref.sharedPreferences = null;
return result;
}
Now, I am trying to retrieve the data which I stored in SharedPreferences.
Here is the code I used to retrieve the data:
String labels = Pref.getValue(mActivity, AppPrefrences.PREF_LABELS, "");
When I debug the app, I get values in Labels below format. The same number of records I received.
The format goes like this:
{572=com.*****.landlord.model.LabelModel#23a282e, 598=com.*****.landlord.model.LabelModel#c954fcf, 590=com.*****.landlord.model.LabelModel#2fe3d5c, 103=com.*****..........}
How can I get the each data from this format?
There is no support for HashMap in SharedPreferences. So, you can't save the HashMap by converting it to a string directly, but you can convert it to JSON string. You can use google-gson in this case. Something like this:
First, include the dependency:
compile 'com.google.code.gson:gson:2.8.2'
Saving from HashMap object to preference:
Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(map);
prefsEditor.putString("YourHashMap", json);
prefsEditor.commit();
Get HashMap object from preference:
Gson gson = new Gson();
String json = mPrefs.getString("YourHashMap", "");
HashMap map = gson.fromJson(json, HashMap.class);
Instead convert the map to gson String and store it in preference like this
//convert to string using gson
Gson gson = new Gson();
String mapString = gson.toJson(map);
//save this in the shared prefs
SharedPreferences prefs = getSharedPreferences("test", MODE_PRIVATE);
prefs.edit().putString("yourkey", mapString).apply();
//get from shared prefs in gson and convert to maps again
String storedHashMapString = prefs.getString("yourkey",null);
java.lang.reflect.Type type = new TypeToken<HashMap<String, String>>(){}.getType();
//Get the hashMap
HashMap<String, String> map = gson.fromJson(storedHashMapString, type);
You are getting {572=com.*****.landlord.model.LabelModel#23a282e, 598=com.*****.landlord.model.LabelModel#c954fcf, 590=com.*****.landlord.model.LabelModel#2fe3d5c, 103=com.*****..........} this because Object default toString() method use hashcode.
Storing complex object in SharedPreference is not recommended. SharedPreference don't support HashMap link.
For storing simple object you have to convert the object into String using toString() method.
You can use Gson for converting object to String and that will be a easy solution.
You can also use ObjectOutputStream to write it to the internal memory check this link
You should cast lables string into hashmap object This is one solution. If you want to make it more generic, you can us StringUtils library.
String value = "{first_name = mohit,last_name = mathur,gender = male}";
value = value.substring(1, value.length()-1); //remove curly brackets
String[] keyValuePairs = value.split(","); //split the string to creat key-value pairs
Map<String,String> map = new HashMap<>();
for(String pair : keyValuePairs) //iterate over the pairs
{
String[] entry = pair.split("="); //split the pairs to get key and value
map.put(entry[0].trim(), entry[1].trim()); //add them to the hashmap and trim whitespaces
}
For example, you can switch
value = value.substring(1, value.length()-1);
to
value = StringUtils.substringBetween(value, "{", "}");
and after that
You should cast value in LabelModel
like
LabelModel labels = map.get("598");
SharedPreference doesn't support store map object. https://developer.android.com/reference/android/content/SharedPreferences.Editor.html. So your code just store data obj.toString, that why you see result in debug. If you want to store a map, you can store as json and use put string.

how to Parse Map value Data in android

Map<String, String> map =dataSnapshot.getValue(Map.class);
String MR_ID = map.get("MR_ID");
String JOB_TITLE = map.get("JOB_TITLE");
String JOB_TYPE = map.get("JOB_TYPE");
String Delv_ADDR=map.get("Delv_ADDR");
DataSnapshot { key = platformdb, value =
{MR_RELATIONS={CUSTOMERS={ORDERS={INVENTORY=, Delv_ADDR=D-103
LaxmiNagar New Delhi, ORDER_ID=}}}, MR_SCHEDULE={MR_ID=, JOB_TITLE=,
GEO_LINK=, JOB_TYPE={TSP={TSP_ADDR=, TSP_ID=, GEO_LINK=, TSP_NAME=},
SCC={SCC_ID=, SCC_ADDR=, GEO_LINK=, SCC_NAME=}, CUSTOMER={GEO_LINK=,
CUST_NAME=, CUST_ID=, CUST_ADDR=}}, JOB_ID=, TRANS_SRC=, TRANS_DEST=},
MR_POOL={FREE_MR=, BUSY_MR={77889992222={IS_BUSY=false,
GEO_LINK=8yyttrd}}}} }
This is my Data i am getting in map i want to Parse and and get value of Delv_ADDR But i am unable to get i am getting Null value please suggest me how to get data of that
From the attached input it seems that there is only one entry in the map with key platformdb and value as MR_RELATIONS=....
If you are doing String MR_ID = map.get("MR_ID"); then it will probably return you null as there is no entry in the map with key MR_ID.
What you should be doing instead is retrieve the value against the key by doing the following:
String response = map.get("platformdb");
And then parse this response String to extract the desired values.
Since, response does not seems to be JSON you can try using native String functions.
For example, to extract MR_ID from response you can do the following:
String response = map.get("platformdb");
String MR_ID = response.substring(response.indexOf("MR_ID=") + 6,
response.indexOf("MR_ID=") + response.indexOf(","));
String Delv_ADDR = response.substring(response.indexOf("Delv_ADDR=") + 10,
response.indexOf("Delv_ADDR=") + response.indexOf(","));

Decoding JSON in Java

im really new to java through Eclipse android, and im trying to decode this line of JSON
{"FullName":"bobby Bloggs"}
But when i try to put it into an array through
JSONObject jsonObject = new JSONObject(httpData);
JSONObject feedObject = jsonObject.getJSONObject("FullName");
I hit an exception of
org.json.JSONException: Value bobby Bloggs at FullName of type java.lang.String cannot be converted to JSONObject
Thanks
You are trying to read a String, since {} within the JSON means it is an object. Everything between "" means it's a string. true/false a boolean (getBoolean) and numbers are an Integer (getInteger). Since you want the String you need to use.
String FullName = JSONObject.getString("FullName");
You are trying to get JSONObject out of JSON Object i.e jsonObject.getJSONObject("FullName"); and again assigning to JSONObject.
As suggested by Emanuel use getString to get the data of "FullName" as and assign to a String.
JSONObject jsonObj = new JSONObject(httpData);
String FullName = jsonObj.getString("FullName");
will work.

Categories