JAVA Json object with '=' instead of ':' - java

I have a string in java, that has a JSON structure, but instead of using ':' my string uses '='. so for example I have this string:
[{
index1 = val1,
index2 = val2,
index3 = val3&val4=inside_value
}]
instead of like this:
[{
index1 : val1,
index2 : val2,
index3 : val3&val4=inside_value
}]
now, I can use some costume parser that I can build, but I guess there is already something that works.
any ideas please?

You can go for custom parsing if the string structure is permanent
String convertToJson="[{"
+"index1 = val1,"
+"index2 = val2,"
+"index3 = val3&val4=inside_value"
+"}]";
String[] split1= convertToJson.split(",");
HashMap<String, String> map=new HashMap<>();
for(String row:split1){
row =row.toLowerCase().replaceAll("[\\[\\]\\{\\}]", "");
String key=row.split("=",2)[0];
String value=row.split("=",2)[1];
map.put(key, value);
}
System.out.println("map :: "+map.toString());
JSONObject json = new JSONObject();
json.putAll( map );
System.out.printf( "JSON:", json.toString() );
It is possible to create hashmap from your string by removing unwanted characters and finally create a JSONObject from the hashmap

Related

How to convert a jsonobject into a jsonarray and also change all keys with all custom same keys in Java and Android

Code:
Map<String, Integer> map = new LinkedHashMap<>();
for (int j = 0; j < jsonArray.length(); j++) {
JSONObject list = jsonArray.getJSONObject(j);
String key = list.getString("symbol") + list.getString("groupname");
if (!map.containsKey(key)) {
map.put(key, list.getInt("openqty"));
} else {
int val = map.get(key) + list.getInt("openqty");
map.put(key, val);
}
System.out.println("map " + map);
}
// Converted map into jsonstring
String jsonString = new JSONObject(map).toString();
System.out.println("jsonstring " + jsonString);
Output:
{"SILVERRohit":0,"DINRCosmic":20,"NATURALGASCosmic":0,"NGCosmic":0,"SICosmic":-5,"SILVERCosmic":35,"DINRRishi":0,"SIRishi":0,"SILVERRishi":0,"CLAmitTA":-6,
"CRUDEOILAmitTA":60,"DINRAmitTA":24,"GCAmitTA":0,"GOLDAmitTA":0,"SIAmitTA":0,"SILVERAmitTA":0,"DINRPraveen":0,"GCPraveen":0,"GOLDPraveen":0,"DINRHarsh":46,
"GCHarsh":-9,"GOLDHarsh":28,"SIHarsh":9,"SILVERHarsh":-45,"DINRGovind":-160,"SIGovind":11}
^^ this is an jsonobject I have got by using linkedhashmap. So, now my problem is I want to convert it into jsonArray format to set in the model (recyclerview). I have also tried by iterating, but I am getting the same values in each single row.
Not only this, but also I want to change all jsonobject keys to "open", so that I can use this in recyclerview for each single row.
Expected output:
[ {"open":0},{"open":20} , {"open":0} , {"open":0} ,{"open":-5 } ,
{"open":35 } , {"open":0} ,{"open":0 },{"open":0 } ,{"open":-6 },
{"open":60},{"open":24},{"open":0},{"open":0},{"open":0},
{"open":0},{"open":0},{"open":0},{"open":0},{"open":46},
{"open":-9},{"open":28},{"open":9},{"open":-45},
{"open":-160},{"open":11} ]
As you got the hashmap, iterate the map like this:
Map<String,String> data = MapUtil.newHashMap();
JSONArray jsonArray = new JSONArray();
for (Map.Entry<String, String> entry : data.entrySet()) {
Map<String,String> json = MapUtil.newHashMap();
json.put("open", entry.getValue());
jsonArray.add(json);
}
return jsonArray;

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;

String to map conversion java

Code:
Map test = new HashMap<String,String>();
test.put("1", "erica");
test.put("2", "frog");
System.out.println(test.toString());
This code gives output as :
{1=erica, 2=frog}
I want this output to be again put in a map as key value-pair .
Any suggestions how can i implement this ?
Or is ther any predefined utility class for conversion of the output to HashMap again ?
For me a proper way would be to use a JSON parser like Jackson since the way a HashMap is serialized is not meant to be parsed after such that if you use specific characters like = or , they won't be escaped which makes it unparsable.
How to serialize a Map with Jackson?
ObjectMapper mapper = new ObjectMapper();
String result = mapper.writeValueAsString(myMap);
How to deserialize a String to get a Map with Jackson?
ObjectMapper mapper = new ObjectMapper();
Map map = mapper.readValue(contentToParse, Map.class);
You can try to use this:
String[] tk = mystring.split(" |=");
Map<String, String> map = new HashMap<>();
for (int i=0; i < tk.length-1; i++)
{
map.put(tk[i], tk[i]);
}
return map;
If you want to replicate the Java code filling the map, you may use something like this:
StringBuilder sb = new StringBuilder("Map<String, String> test = new HashMap<>();");
for(Map.Entry<?, ?> entry : test.entrySet())
{
sb.append("\ntest.put(\"");
sb.append(entry.getKey());
sb.append("\", \"");
sb.append(entry.getValue());
sb.append("\");");
}
String string = sb.toString();
System.out.println(string);
But I agree with the comments, that in many applications a format such as JSON is more appropriate to serialize a map.
Note that the above solution does not escape strings, it only works if the strings don't contain characters like " or \n. If you need to handle these cases it will become more complicated.
You could try the following:
String out = test.toString();
Map<String, String> newMap = new HashMap();
// remove the first and last "{", "}"
out = out.subString(1,out.size()-1)
String[] newOut = out.split(", ");
for (int i=0; i<newOut.length;i++){
// keyValue is size of 2. cell 0 is key, cell 1 is value
String[] keyValue = newOut.split("=");
newMap.put(keyValue[0], keyValue[1]);
}
I haven't tested the code in java i just wrote from my mind. I hope it will work

Putting JSON values into Hashmap

I have JSON value like below,
{ "emp_id": 1017,
"emp_name": "karthik Y",
"emp_designation": "Manager",
"department": "JavaJson",
"salary": 30000,
"direct_reports":
[
"Nataraj G",
"Kalyan",
"Mahitha"
]
}
HashMap < String, String[] >input1 = new HashMap < String, String[] >();
input1.put("empid","1017");
input1.put("emp_name","karthik");
input1.put("emp_designation","manager");
input1.put("salary","30000");
now I want to add next array that is direct_report to put as next key and value(entire array shoud be come one key and value). Someone please help out.
Hashmap is a key/value storage, where keys are unique. You can convert your JSON to string and then store it as a value to the hashmap. For example something like below:
public static void main(String[] args) {
String json = "{ \"emp_id\": 1017,"
+ "\"emp_name\": \"karthik Y\","
+ "\"emp_designation\": \"Manager\","
+ "\"department\": \"JavaJson\","
+ "\"salary\": 30000,"
+ "\"direct_reports\": ["
+ "\"Nataraj G\","
+ "\"Kalyan\","
+ "\"Mahitha\"]}";
HashMap<String, String> jsonStore = new HashMap<String, String>();
jsonStore.put("myJson", json);
System.out.println(jsonStore.get("myJson"));
}
You need can also use the 'org.json' library to
Create JSON object manually
Convert existing JSONObject to String representation
Convert JSON string to JSONObject
You can also have the following solution:
JSONObject jsonObject = new JSONObject();
jsonObject.put("empt_id", 1017);
jsonObject.put("emp_name", "karthik");
HashMap<String, JSONObject> jsonObjectStore = new HashMap<String, JSONObject>();
jsonObjectStore.put("myJsonObject", jsonObject);
HashMap<JSONObject, String> jsonObjectStore2 = new HashMap<JSONObject, String>();
jsonObjectStore2.put(jsonObject, "myJson");
Make sure that you download the org.json jar file and put it in your classpath to be able to use the JSONObject. You can download the jar from here.
In order to put each of those values into map as single key/value entry. You have mentioned it yourself, it should work without any problem. See below methods:
Method 1
Everything in Java is Object, String inherits Object, String[] inherits object. You can have the following solution:
HashMap<String, Object> myObjectStore4 = new HashMap<String, Object>();
String[] directReports4 = new String[]{"Natraj G", "Kalyan", "Mahitha"};
myObjectStore4.put("emp_id", new String("123"));
myObjectStore4.put("emp_name", new String("Raf"));
// others ....
myObjectStore4.put("directReports", directReports4);
Method 2
To store the fields as key/value and if you can afford converting the array to String (which represents all array elements comma separated then use this method).
HashMap<String, String> myObjectStoreTwo = new HashMap<String, String>();
String[] directReports2 = new String[]{"Natraj G", "Kalyan", "Mahitha"};
myObjectStoreTwo.put("emp_id", "123");
myObjectStoreTwo.put("emp_name", "Raf");
myObjectStoreTwo.put("salary", "222");
//Converts array to comma separated String
myObjectStoreTwo.put("directReports",Arrays.toString(directReports2));
Method 3
In the expense of having Hash Map to store String key and Array value. You have to put other elements as array too.
HashMap<String, String[]> myObjectStore3 = new HashMap<String, String[]>();
String[] directReports3 = new String[]{"Natraj G", "Kalyan", "Mahitha"};
myObjectStore3.put("emp_id", new String[]{123 + ""});
myObjectStore3.put("salary", new String[]{32312 + ""});
myObjectStore3.put("directReports", directReports3);
Use a jackson ObjectMapper. Try if this works
String json = "{....}"
HashMap<String,Object> mappedVals = new ObjectMapper().readValue(
json ,
new TypeReference<HashMap<String,Object>>() {
});

Convert JSON object with duplicate keys to JSON array

I have a JSON string that I get from a database which contains repeated keys. I want to remove the repeated keys by combining their values into an array.
For example
Input
{
"a":"b",
"c":"d",
"c":"e",
"f":"g"
}
Output
{
"a":"b",
"c":["d","e"],
"f":"g"
}
The actual data is a large file that may be nested. I will not know ahead of time what or how many pairs there are.
I need to use Java for this. org.json throws an exception because of the repeated keys, gson can parse the string but each repeated key overwrites the last one. I need to keep all the data.
If possible, I'd like to do this without editing any library code
As of today the org.json library version 20170516 provides accumulate() method that stores the duplicate key entries into JSONArray
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("a", "b");
jsonObject.accumulate("c", "d");
jsonObject.accumulate("c", "e");
jsonObject.accumulate("f", "g");
System.out.println(jsonObject);
Output:
{
"a":"b",
"c":["d","e"],
"f":"g"
}
I want to remove the repeated keys by combining their values into an array.
Think other than JSON parsing library. It's very simple Java Program using String.split() method that convert Json String into Map<String, List<String>> without using any library.
Sample code:
String jsonString = ...
// remove enclosing braces and double quotes
jsonString = jsonString.substring(2, jsonString.length() - 2);
Map<String, List<String>> map = new HashMap<String, List<String>>();
for (String values : jsonString.split("\",\"")) {
String[] keyValue = values.split("\":\"");
String key = keyValue[0];
String value = keyValue[1];
if (!map.containsKey(key)) {
map.put(key, new ArrayList<String>());
}
map.get(key).add(value);
}
output:
{
"f": ["g"],
"c": ["d","e"],
"a": ["b"]
}
In order to accomplish what you want, you need to create some sort of custom class since JSON cannot technically have 2 values at one key. Below is an example:
public class SomeClass {
Map<String, List<Object>> values = new HashMap<String, List<Object>>();
public void add(String key, Object o) {
List<Object> value = new ArrayList<Object>();
if (values.containsKey(key)) {
value = values.get(key);
}
value.add(o);
values.put(key, value);
}
public JSONObject toJson() throws JSONException {
JSONObject json = new JSONObject();
JSONArray tempArray = null;
for (Entry<String, List<Object>> en : values.entrySet()) {
tempArray = new JSONArray();
for (Object o : en.getValue()) {
tempArray.add(o);
}
json.put(en.getKey(), tempArray);
}
return json;
}
}
You can then retrieve the values from the database, call the .add(String key, Object o) function with the column name from the database, and the value (as the Object param). Then call .toJson() when you are finished.
Thanks to Mike Elofson and Braj for helping me in the right direction. I only wanted to have the keys with multiple values become arrays so I had to modify the code a bit. Eventually I want it to work for nested JSON as well, as it currently assumes it is flat. However, the following code works for what I need it for at the moment.
public static String repeatedKeysToArrays(String jsonIn) throws JSONException
{
//This assumes that the json is flat
String jsonString = jsonIn.substring(2, jsonIn.length() - 2);
JSONObject obj = new JSONObject();
for (String values : jsonString.split("\",\"")) {
String[] keyValue = values.split("\":\"");
String key = keyValue[0];
String value = "";
if (keyValue.length>1) value = keyValue[1];
if (!obj.has(key)) {
obj.put(key, value);
} else {
Object Oold = obj.get(key);
ArrayList<String> newlist = new ArrayList<String>();
//Try to cast as JSONArray. Otherwise, assume it is a String
if (Oold.getClass().equals(JSONArray.class)) {
JSONArray old = (JSONArray)Oold;
//Build replacement value
for (int i=0; i<old.length(); i++) {
newlist.add( old.getString(i) );
}
}
else if (Oold.getClass().equals(String.class)) newlist = new ArrayList<String>(Arrays.asList(new String[] {(String)Oold}));
newlist.add(value);
JSONArray newarr = new JSONArray( newlist );
obj.put(key,newarr);
}
}
return obj.toString();
}

Categories