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:25

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));
查看更多
妖精总统
3楼-- · 2019-01-01 05:28

You can use XStream - it is really handy. See the examples here

package com.thoughtworks.xstream.json.test;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JettisonMappedXmlDriver;

public class WriteTest {

    public static void main(String[] args) {

      HashMap<String,String> map = new HashMap<String,String>();
      map.add("1", "a");
      map.add("2", "b");
      XStream xstream = new XStream(new JettisonMappedXmlDriver());

      System.out.println(xstream.toXML(map));       

    }

}
查看更多
妖精总统
4楼-- · 2019-01-01 05:28

If you are using net.sf.json.JSONObject then you won't find a JSONObject(map) constructor in it. You have to use the public static JSONObject fromObject( Object object ) method. This method accepts JSON formatted strings, Maps, DynaBeans and JavaBeans.

JSONObject jsonObject = JSONObject.fromObject(myMap);

查看更多
若你有天会懂
5楼-- · 2019-01-01 05:31

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:

import play.api.libs.json.{JsValue, Json}
import scala.collection.JavaConversions.mapAsScalaMap


object JsonParser {

  def parse(map: Map[String, Any]): JsValue = {
    val values = for((key, value) <- map) yield {
      value match {
        case m: java.util.Map[String, _] @unchecked => Json.obj(key -> parse(m.toMap))
        case m: Map[String, _] @unchecked => Json.obj(key -> parse(m))
        case int: Int => Json.obj(key -> int)
        case str: String => Json.obj(key -> str)
        case bool: Boolean => Json.obj(key -> bool)
      }
    }

    values.foldLeft(Json.obj())((temp, obj) => {
      temp.deepMerge(obj)
    })
  }
}

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.

查看更多
浮光初槿花落
6楼-- · 2019-01-01 05:32
    import org.json.JSONObject;

    HashMap<Object, Object> map = new HashMap<>();
    String[] list={"Grader","Participant"};
    String[] list1={"Assistant","intern"};
    map.put("TeachingAssistant",list);
    map.put("Writer",list1);
    JSONObject jsonObject = new JSONObject(map);
    System.out.printf(jsonObject.toString());

    // Result: {"TeachingAssistant":["Grader","Participant"],"Writer":["Assistant","intern"]}
查看更多
梦该遗忘
7楼-- · 2019-01-01 05:34

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.

查看更多
登录 后发表回答