带有fastjson解析对象错误的kotlin:找不到默认构造函数

时间:2018-12-31 03:01:20

标签: kotlin fastjson

我正在尝试在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

1 个答案:

答案 0 :(得分:0)

我认为这是一个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)