Scala/Play: parse JSON into Map instead of JsObject

前端 未结 5 1163
小蘑菇
小蘑菇 2020-12-24 14:04

On Play Framework\'s homepage they claim that \"JSON is a first class citizen\". I have yet to see the proof of that.

In my project I\'m dealing with some pretty co

5条回答
  •  爱一瞬间的悲伤
    2020-12-24 14:27

    Would recommend reading up on pattern matching and recursive ADTs in general to better understand of why Play Json treats JSON as a "first class citizen".

    That being said, many Java-first APIs (like Google Java libraries) expect JSON deserialized as Map[String, Object]. While you can very simply create your own function that recursively generates this object with pattern matching, the simplest solution would probably be to use the following existing pattern:

    import com.google.gson.Gson
    import java.util.{Map => JMap, LinkedHashMap}
    
    val gson = new Gson()
    
    def decode(encoded: String): JMap[String, Object] =   
       gson.fromJson(encoded, (new LinkedHashMap[String, Object]()).getClass)
    

    The LinkedHashMap is used if you would like to maintain key ordering at the time of deserialization (a HashMap can be used if ordering doesn't matter). Full example here.

提交回复
热议问题