renameing keys in Json using Java

I have a json string and a mapping. I want to rename all the keys in the json string according to the map.

eg. json ={"dd":"12","dt":14","df":"55"}
and map = "dd":"date_dd","df":"date_df"

then my output should be {"date_dd":"12","dt":14","date_df":"55"}

The mapping basically provides the renamed values of certain keys and we have to replace all the key names which fall in the mapping which the new name.

Rohit BajajAsked:
Who is Participating?
mccarlConnect With a Mentor IT Business Systems Analyst / Software DeveloperCommented:
I can think of (at least) two ways of doing this, one is fairly simple but wouldn't be very robust in the face of slight changes in the input json, the other way more complex but could handle all sorts of input in a better fashion. Before I go into too much detail about either, could you let me know which general method you would be more likely to prefer...

Simple way: would be to just iterate through the entries in your "map" and then search for the key (ie. "dd" or "df") and then just do a String.replaceAll to change that key to the value. Note you would have to add a little bit of logic to attempt to make it only replace keys that match and NOT perform the replace if "dd" appeared in the value part of the JSON. This is where the potential for problems may surface, but if your JSON will always be fairly simple than this may be an acceptable solution
Complex way: would be to parse the JSON input with a 3rd party library like Jackson, which will result in a Map itself, then one could iterate through this map, and if any keys from the JSON map are present in the other map, you could remove that entry and put another one in with the correct key name (I hope all those references to 'maps' are clear!). Then you can use Jackson again to marshall the modified map back into a JSON string. Obviously, this is cleaner in terms that it will definitely only modify 'key' names and not values and handle a few more variances in possible JSON input but it will then depend on a 3rd party library and could possibly be a little bit slower in terms of performance. However, if your end goal is to parse this string input to something more useable anyway, then these points are irrelevant

Let us know what you think and then I can expand further on the solution you would prefer!
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.