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 convert
Map
toJSON
usingJackson
as follows:Maven Dependencies for
Jackson
:If you are using
JSONObject
library, you can convert map toJSON
as follows:Maven Dependencies for
JSONObject
:Hope this will help. Happy coding.
Late to the party but here is my GSON adhoc writer for serializing hashmap. I had to write map of key-value pairs as json string attributes, expect one specific to be integer type. I did not want to create custom JavaBean wrapper for this simple usecase.
GSON JsonWriter class is easy to use serializer class containing few strongly typed writer.value() functions.
If none of the custom types be needed I could have just use toJson() function. gson-2.2.4.jar library is just under 190KB without any brutal dependencies. Easy to use on any custom servlet app or standalone application without big framework integrations.
I'm using Alibaba fastjson, easy and simple:
and import:
Then:
Everything is ok.
Example using json
output::
You can also try to use Google's GSON.Google's GSON is the best library available to convert Java Objects into their JSON representation.
http://code.google.com/p/google-gson/
this works for me :