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
You can use Gson. This library provides simple methods to convert Java objects to JSON objects and vice-versa.
Example:
You can use a GsonBuilder when you need to set configuration options other than the default. In the above example, the conversion process will also serialize null attributes from object.
However, this approach only works for non-generic types. For generic types you need to use toJson(object, Type).
More information about Gson here.
Remember that the object must implement the Serializable interface.
In my case I didn't want any dependancies. Using Java 8 you can get JSON as a string this simple:
If you use complex objects, you should apply enableComplexMapKeySerialization(), as stated in https://stackoverflow.com/a/24635655/2914140 and https://stackoverflow.com/a/26374888/2914140.
Output will be:
You can just enumerate the map and add the key-value pairs to the JSONObject
Method :
If you need use it in the code.
Here my single-line solution with GSON: