How to convert hashmap to JSON object in Java

2019-01-01 04:55发布

How to convert or cast hashmap to JSON object in Java, and again convert JSON object to JSON string?

标签: java json
23条回答
皆成旧梦
2楼-- · 2019-01-01 05:41

You can convert Map to JSON using Jackson as follows:

Map<String,Object> map = new HashMap<>();
//You can convert any Object.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
map.put("key3","string1");
map.put("key4","string2");

String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);

Maven Dependencies for Jackson :

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

If you are using JSONObject library, you can convert map to JSON as follows:

Map<String, Object> map = new HashMap<>();
// Convert a map having list of values.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);

JSONObject json = new JSONObject(map);
System.out.println(json);

Maven Dependencies for JSONObject :

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>

Hope this will help. Happy coding.

查看更多
旧时光的记忆
3楼-- · 2019-01-01 05:41

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.

// write Map as JSON document to http servlet response
Map<String,String> sd = DAO.getSD(123);
res.setContentType("application/json; charset=UTF-8");
res.setCharacterEncoding("UTF-8");
JsonWriter writer = new JsonWriter(new OutputStreamWriter(res.getOutputStream(), "UTF-8"));
writer.beginObject();
for(String key : sd.keySet()) {
    String val = sd.get(key);
    writer.name(key);
    if (key.equals("UniqueID") && val!=null)
        writer.value(Long.parseLong(val));
    else
        writer.value(val);
}
writer.endObject();
writer.close();

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.

Gson gson = new Gson(); 
String json = gson.toJson(myMap); 
查看更多
只若初见
4楼-- · 2019-01-01 05:41

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.

查看更多
旧人旧事旧时光
5楼-- · 2019-01-01 05:42

Example using json

Map<String, Object> data = new HashMap<String, Object>();
    data.put( "name", "Mars" );
    data.put( "age", 32 );
    data.put( "city", "NY" );
    JSONObject json = new JSONObject();
    json.putAll( data );
    System.out.printf( "JSON: %s", json.toString(2) );

output::

JSON: {
  "age": 32,
  "name": "Mars",
  "city": "NY"
}

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/

查看更多
琉璃瓶的回忆
6楼-- · 2019-01-01 05:45

this works for me :

import groovy.json.JsonBuilder
properties = new Properties()
properties.put("name", "zhangsan")

println new JsonBuilder(properties).toPrettyString()
查看更多
登录 后发表回答