Bootstrap

scala中json转换问题

问题: scala中对象转json字符串报错

提示:scala中get和set方法实现与java中的不一样。

Error:(26, 10) ambiguous reference to overloaded definition,
both method toJSONString in class JSON of type (x$1: Any, x$2: com.alibaba.fastjson.serializer.SerializerFeature*)String
and  method toJSONString in class JSON of type (x$1: Any)String
match argument types (com.yupaopao.platform.common.dto.Response[com.yupaopao.platform.common.dto.PageResult[com.yupaopao.platform.rank.api.response.TopsRankDTO]]) and expected result type String
    JSON.toJSONString(accompany_rank)

一、使用fastjson或者json4s

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>2.0.23</version>
</dependency>

<dependency>
  <groupId>org.json4s</groupId>
  <artifactId>json4s-jackson_${scala.version}</artifactId>
  <version>3.2.11</version>
</dependency>

1、使用fastjson

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.{SerializeConfig, SerializerFeature}

case class Person(id: Integer, name: String, item: String)
object test {
  def main(args: Array[String]): Unit = {

    val od = Order(1,"01",null)
    val jsonString = JSON.toJSONString(od, new SerializeConfig(true),SerializerFeature.WriteMapNullValue)
    println(jsonString)    #结果:{"id":1,"name":"01","item":null}


    val obj = JSON.parseObject(jsonString, classOf[Person])
    println(obj)          #结果:Person(1,01,null)

  }
}

补充:scala case class + BeanProperty+fastjson

2、使用json4s

import org.json4s._
import org.json4s.jackson.{JsonMethods, Serialization}

case class Person(id: Int, name: String, item: String)
object test {
  def main(args: Array[String]): Unit = {

    #隐式转换
    implicit val formats = Serialization.formats(NoTypeHints)

    #对象转jsonString
    val od = Person(1,"01",null)
    val jsonString = Serialization.write(od)
    println(jsonString)    #结果:{"id":1,"name":"01","item":null}

    #jsonString转对象
    val person = JsonMethods.parse(jsonString).extract[Person]
    println(person)        #结果:Person(1,01,null)  

  }
}

;