How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?
For those using org.json.simple.JSONObject
, you could convert the map to Json String and parse it to get the JSONObject
.
JSONObject object = (JSONObject) new JSONParser().parse(JSONObject.toJSONString(map));
Gson can also be used to serialize arbitrarily complex objects.
Here is how you use it:
Gson gson = new Gson();
String json = gson.toJson(myObject);
Gson
will automatically convert collections to JSON
arrays. Gson can serialize private fields and automatically ignores transient fields.
If you don't really need HashMap then you can do something like that:
String jsonString = new JSONObject() {{
put("firstName", user.firstName);
put("lastName", user.lastName);
}}.toString();
Output:
{
"firstName": "John",
"lastName": "Doe"
}
I'm using Alibaba fastjson, easy and simple:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>VERSION_CODE</version>
</dependency>
and import:
import com.alibaba.fastjson.JSON;
Then:
String text = JSON.toJSONString(obj); // serialize
VO vo = JSON.parseObject("{...}", VO.class); //unserialize
Everything is ok.
If you need use it in the code.
Gson gsone = new Gson();
JsonObject res = gsone.toJsonTree(sqlParams).getAsJsonObject();
I found another way to handle it.
Map obj=new HashMap();
obj.put("name","sonoo");
obj.put("age",new Integer(27));
obj.put("salary",new Double(600000));
String jsonText = JSONValue.toJSONString(obj);
System.out.print(jsonText);
Hope this helps.
Thanks.