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
Related
All I have is the request URI from which I have to parse the query params. What I'm doing is adding them to json/hashmap and fetching again like the following
String requestUri = "name=raju&school=abcd&college=mnop&color=black&fruit=mango";
All I have to do is to finally assign it to variables like the following
String name = "raju";
String school = "abcd";
String college = "mnop";
String color = "black";
String fruit = "mango";
So I am parsing the request uri like the following
String[] paramsKV = requestUri.split("&");
JSONArray jsonKVArr = new JSONArray();
for (String params : paramsKV) {
String[] tempArr = params.split("=");
if(tempArr.length>1) {
String key = tempArr[0];
String value = tempArr[1];
JSONObject jsonObj = new JSONObject();
jsonObj.put(key, value);
jsonKVArr.put(jsonObj);
}
}
The another way is to populate the same in hash map and obtain the same. The other way is to match the requestUri string with regex pattern and obtain the results.
Say for an example to get the value of school I have to match the values between the starting point of the string school and the next & - which doesn't sound good.
What is the better approach to parse the query String in java?
How could i handle the following thing in a better way?
I need to construct another hash map like the following from the above results like
Map<String, String> resultMap = new HashMap<String, String>;
resultMap.put("empname", name);
resultMap.put("rschool", school);
resultMap.put("empcollege", college);
resultMap.put("favcolor", color);
resultMap.put("favfruit", fruit);
To make it simple all I have to do is to parse the query param and construct a hashMap by naming the key filed differently. How could I do it in a simple way? Any help in this is much appreciated.
Short answer: Every HTTP Client library will do this for you.
Example: Apache HttpClient's URLEncodedUtils class
String queryComponent = "name=raju&school=abcd&college=mnop&color=black&fruit=mango";
List<NameValuePair> params = URLEncodedUtils.parse(queryComponent, Charset.forName("UTF-8"));
They're basically approaching it the same way. Parameter key-value pairs are delimited by & and the keys from the values by = so String's split is appropriate for both.
From what I can tell however your hashmap inserts are mapping new keys to the existing values so there's really no optimization, save maybe for moving to a Java 8 Stream for readability/maintenance and/or discarding the initial jsonArray and mapping straight to the hashmap.
Here is another possible solution:
Pattern pat = Pattern.compile("([^&=]+)=([^&]*)");
Matcher matcher = pat.matcher(requestUri);
Map<String,String> map = new HashMap<>();
while (matcher.find()) {
map.put(matcher.group(1), matcher.group(2));
}
System.out.println(map);
You can use Java 8 and store your data in HashMap in one operation.
Map<String,String> map = Pattern.compile("\\s*&\\s*")
.splitAsStream(requestUri.trim())
.map(s -> s.split("=", 2))
.collect(Collectors.toMap(a -> a[0], a -> a.length > 1 ? a[1]: ""));
You can do it by Jersey library (com.sun.jersey.api.uri.UriComponent or org.glassfish.jersey.uri.UriComponent class):
String queryComponent = "name=raju&school=abcd&college=mnop&color=black&fruit=mango";
MultivaluedMap<String, String> params = UriComponent.decodeQuery(queryComponent, true);
Use jackson json parser. Maven dependency:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
Now use ObjectMapper to create Map from json string:
ObjectMapper mapper = new ObjectMapper();
Map list = mapper.readValue(requestUri, Map.class);
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>>() {
});
I have sets of strings that look like this:
[{"tag":"rat","score":0.7973},{"tag":"lion","score":0.7184},{"tag":"dog","score":0.2396},{"tag":"woof","score":0.1944},{"tag":"cat","score":0.1157}]
I would like to print the following in order from the string:
rat
lion
dog
woof
cat
How can i do this?
Proper use any JSON parsing library such as GSON or Jackson and convert it into Java Object.
Note: It returns java.util.LinkedHashMap that maintains the order.
Sample code:
GSON
String jsonString="[{\"tag\":\"rat\",\"score\":0.7973},{\"tag\":\"lion\",\"score\":0.7184},{\"tag\":\"dog\",\"score\":0.2396},{\"tag\":\"woof\",\"score\":0.1944},{\"tag\":\"cat\",\"score\":0.1157}]";
Type type = new TypeToken<ArrayList<Map<String, String>>>() {}.getType();
ArrayList<Map<String, String>> data = new Gson().fromJson(jsonString, type);
for (Map<String, String> map : data) {
System.out.println(map.get("tag"));
}
Jackson
String jsonString="[{\"tag\":\"rat\",\"score\":0.7973},{\"tag\":\"lion\",\"score\":0.7184},{\"tag\":\"dog\",\"score\":0.2396},{\"tag\":\"woof\",\"score\":0.1944},{\"tag\":\"cat\",\"score\":0.1157}]";
TypeReference<ArrayList<Map<String, String>>> typeRef = new TypeReference<ArrayList<Map<String, String>>>() {};
ObjectMapper mapper = new ObjectMapper();
try {
ArrayList<Map<String, String>> data = mapper.readValue(jsonString, typeRef);
for (Map<String, String> map : data) {
System.out.println(map.get("tag"));
}
} catch (Exception e) {
System.out.println("There might be some issue with the JSON string");
}
output:
rat
lion
dog
woof
cat
(?:.*?{"tag":)"(.*?)",.*?}
This will match all the required groups.See Demo
http://regex101.com/r/aN1bX5/1
This string is JSON so you could use a JSON parser to do this.
If you're looking for an easy way to get all the values of "tag" use this regex and extract group 1 in Java.
"tag":"((?:[^"\\]|\\.)*)"
Debuggex Demo
Double-escape this if you're gonna use it in Java:
Pattern p = Pattern.compile("\"tag\":\"((?:[^\"\\\\]|\\\\.)*)\"");
Try this. The match is in the first capture group
(?:"tag":"|\G(?!^))([^"]*)
Dont use regex to parse JSON. Use a library like GSON or Jackson
JSONArray jsa = new JSONArray(jsonString);
for (int i = 0; i < jsa.length(); i++) {
JSONObject json = jsa.getJSONObject(i);
System.out.println(json.getString("tag"));
}
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();
}
String input = "key1=value1&key2=value2&key3=value3&key4=value4&key5=value5";
How can I store the key-value pairs into a HashMap object using StringTokenizer?
Using a StringTokenizer would look something like this I guess.
String input = "key1=value1&key2=value2&key3=value3&key4=value4&key5=value5";
StringTokenizer st = new StringTokenizer(input, "&");
Map<String, String> map = new HashMap<String, String>();
while ( st.hasMoreElements() ) {
String actualElement = st.nextToken();
StringTokenizer et = new StringTokenizer(actualElement, "=");
if ( et.countTokens() != 2 ) {
throw new RuntimeException("Unexpeced format");
}
String key = et.nextToken();
String value = et.nextToken();
map.put(key, value);
}
System.out.println(map);
You could also use String.split(). It looks a little nicer in my opinion.
Map<String, String> map = new HashMap<String, String>();
for ( String actualElement : input.split("&") ) {
map.put(actualElement.split("=")[0],
actualElement.split("=")[1]);
}
System.out.println(map);
Beware that you must make sure that the delimiters (in this case "=" and "&") is not allowed to appear in the data! When the delimiters should be allowed to appear in the data they must be escaped in some way to handle the input properly.
I understand that initial question was referring to the usage of StringTokenizer but it can be done with Splitter from guava in a more easier and concise way:
Map<String, String> map = ImmutableMap.copyOf(Splitter.on('&')
.withKeyValueSeparator("=")
.split(checkNotNull(input)));