• scala中json转换问题


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

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

    1. Error:(26, 10) ambiguous reference to overloaded definition,
    2. both method toJSONString in class JSON of type (x$1: Any, x$2: com.alibaba.fastjson.serializer.SerializerFeature*)String
    3. and method toJSONString in class JSON of type (x$1: Any)String
    4. 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
    5. JSON.toJSONString(accompany_rank)

    一、使用fastjson或者json4s

    1. <dependency>
    2. <groupId>com.alibabagroupId>
    3. <artifactId>fastjsonartifactId>
    4. <version>2.0.23version>
    5. dependency>
    6. <dependency>
    7. <groupId>org.json4sgroupId>
    8. <artifactId>json4s-jackson_${scala.version}artifactId>
    9. <version>3.2.11version>
    10. dependency>

    1、使用fastjson

    1. import com.alibaba.fastjson.JSON
    2. import com.alibaba.fastjson.serializer.{SerializeConfig, SerializerFeature}
    3. case class Person(id: Integer, name: String, item: String)
    4. object test {
    5. def main(args: Array[String]): Unit = {
    6. val od = Order(1,"01",null)
    7. val jsonString = JSON.toJSONString(od, new SerializeConfig(true),SerializerFeature.WriteMapNullValue)
    8. println(jsonString) #结果:{"id":1,"name":"01","item":null}
    9. val obj = JSON.parseObject(jsonString, classOf[Person])
    10. println(obj) #结果:Person(1,01,null)
    11. }
    12. }

    补充:scala case class + BeanProperty+fastjson

    2、使用json4s

    1. import org.json4s._
    2. import org.json4s.jackson.{JsonMethods, Serialization}
    3. case class Person(id: Int, name: String, item: String)
    4. object test {
    5. def main(args: Array[String]): Unit = {
    6. #隐式转换
    7. implicit val formats = Serialization.formats(NoTypeHints)
    8. #对象转jsonString
    9. val od = Person(1,"01",null)
    10. val jsonString = Serialization.write(od)
    11. println(jsonString) #结果:{"id":1,"name":"01","item":null}
    12. #jsonString转对象
    13. val person = JsonMethods.parse(jsonString).extract[Person]
    14. println(person) #结果:Person(1,01,null)
    15. }
    16. }

  • 相关阅读:
    3D视觉识别案例:3D无序棒料抓取,阀体圆环上下料,电机定子上料
    腾讯后端开发高频问题和答案
    【图像分割】基于PCA结合模糊聚类算法FCM实现SAR图像分割附matlab代码
    带你学Java从入门到精通
    数据结构入门 — 栈
    算法(一)
    Redis集群架构搭建——主从、哨兵、集群
    PG::SunsetDecoy
    【0基础学Java第七课】-- 类和对象02
    模型的威力:基于模型,快速梳理源码
  • 原文地址:https://blog.csdn.net/csmnjk/article/details/143326621