我正在尝试在Kotlin代码中使用fastjson解析对象。但是当我使用JSON.parseObject时发生了异常,这是详细信息:

我的数据类:

    import com.alibaba.fastjson.JSONObject

    data class StatesMessage @JvmOverloads constructor(val command: String =
        "states", var states: States = States()) {

      fun toJsonString(): String {
          return JSONObject.toJSONString(this)
      }

      data class States(var x: Double = 0.0, var y: Double = 0.0)
    }

然后我尝试从字符串获取对象:
val state = JSON.parseObject(s, StatesMessage::class.java)

但是从fastjson抛出异常:
Caused by: com.alibaba.fastjson.JSONException: default constructor not found.
    class com.example.demo.StatesMessage
   at com.alibaba.fastjson.util.JavaBeanInfo.build(JavaBeanInfo.java:475)
   at com.alibaba.fastjson.util.JavaBeanInfo.build(JavaBeanInfo.java:221)
   at com.alibaba.fastjson.parser.ParserConfig.createJavaBeanDeserializer(ParserConfig.java:670)
   at com.alibaba.fastjson.parser.ParserConfig.getDeserializer(ParserConfig.java:587)
   at com.alibaba.fastjson.parser.ParserConfig.getDeserializer(ParserConfig.java:398)
   at com.alibaba.fastjson.parser.DefaultJSONParser.parseObject(DefaultJSONParser.java:665)
   at com.alibaba.fastjson.JSON.parseObject(JSON.java:365)
   at com.alibaba.fastjson.JSON.parseObject(JSON.java:269)
   at com.alibaba.fastjson.JSON.parseObject(JSON.java:488)
   at com.example.demo.StartupRunner.run(StartupRunner.kt:25)
   at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:813)
... 5 more

所有代码都参考https://github.com/forest-yang/koltinjson

最佳答案

我认为这是一个fastjson(至1.2.54)错误。
当我改用gson时,它可以工作。

    /* it will throw exception
    val state = JSON.parseObject(s, StatesMessage::class.java)
    */
    val state = Gson().fromJson(s, StatesMessage::class.java)
    logger.info(state.states.x)
    logger.info(state.states.y)

10-08 01:27