scala中对象与map转json

今天需要把一个object对象转为jsonstring,刚开始尝试用fastjson

但是一直报

Error:(14, 18) ambiguous reference to overloaded definition,
both method toJSONString in object JSON of type (x$1: Any, x$2: com.alibaba.fastjson.serializer.SerializerFeature*)String
and  method toJSONString in object JSON of type (x$1: Any)String
match argument types (Map[String,String]) and expected result type Any
    println(JSON.toJSONString(maplevel1))

异常,方法重载异常,需要显示指明调用的哪个方法,

第二放弃fastjson

使用

json4s
测试代码

package project_session_spark.sparkapi

import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.jackson.JsonMethods._


/**
  * Created by jevon.liu on 2017/8/16.
  */
object StringToJson {
  case  class Person(var name:Any, var age:Any) {
  }
  var maplevel1:Map[String,String] = Map()
  maplevel1 += ("apple"-> "苹果");
  var per = Person("liu" , 2)
  per.name = "sssss"
  def main(args: Array[String]): Unit = {
    val jsons1 = compact(render(per.toString))
    println( jsons1)
    val jsons2 = compact(render(maplevel1))
    println(maplevel1)
  }
}
可以将map或者对象转为jsonstring

你可能感兴趣的:(scala中对象与map转json)