How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
For those using
org.json.simple.JSONObject
, you could convert the map to Json String and parse it to get theJSONObject
.You can use XStream - it is really handy. See the examples here
If you are using
net.sf.json.JSONObject
then you won't find aJSONObject(map)
constructor in it. You have to use thepublic static JSONObject fromObject( Object object )
method. This method accepts JSON formatted strings, Maps, DynaBeans and JavaBeans.JSONObject jsonObject = JSONObject.fromObject(myMap);
I faced a similar problem when deserializing the Response from custom commands in selenium. The response was json, but selenium internally translates that into a java.util.HashMap[String, Object]
If you are familiar with scala and use the play-API for JSON, you might benefit from this:
Small code description:
The code recursively traverses through the HashMap until basic types (String, Integer, Boolean) are found. These basic types can be directly wrapped into a JsObject. When the recursion is unfolded, the deepmerge concatenates the created objects.
'@unchecked' takes care of type erasure warnings.
This is typically the work of a Json library, you should not try to do it yourself. All json libraries should implement what you are asking for, and you can find a list of Java Json libraries on json.org, at the bottom of the page.