How to convert hashmap to JSON object in Java

前端 未结 29 2367
谎友^
谎友^ 2020-11-22 11:20

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

29条回答
  •  天涯浪人
    2020-11-22 11:55

    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.

提交回复
热议问题