1

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

4

1 回答 1

1

我认为这是一个 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)
于 2018-12-31T13:50:37.100 回答