Gson适配器未转换为对象

时间:2018-06-22 11:51:11

标签: kotlin jaxb jax-ws

我想将接收到的json转换为java对象。 即,使对象“ customs”包含“ scoreHeader”和“ score”而不是“ JAXBElement” 我的提供程序正在尝试将json映射到对象:

@Stateless
open class GsonProvider {

    private lateinit var gson: Gson

    @PostConstruct
    fun init() {
        gson = GsonBuilder()
                .registerTypeAdapter(JAXBElement::class.java, JaxbElementAdapter())
                .create()
    }

    open fun provide(): Gson {
        return gson
    }
}

适配器:

class JaxbElementAdapter : TypeAdapter<JAXBElement<*>>() {
    override fun write(jsonWriter: JsonWriter, jaxbElement: JAXBElement<*>) {
        jsonWriter.value(if (jaxbElement.value != null) jaxbElement.value.toString() else "")
    }

    override fun read(p0: JsonReader?): JAXBElement<*> {
        print("")
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

以及调用此提供程序的代码:

val object = gsonProvider.provide().toJson(jsonString)

但是我收到以下形式的错误:

Caused by: java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: https.ws.types.ScoreSupplement. Forgot to register a type adapter?

json字符串看起来像这样:

{
   "status":"OK",
   "scores":{
      "customs":[
         {
            "JAXBElement":{
               "name":"risc",
               "declaredType":"https.ws.types.ScoreSupplement",
               "scope":"https.ws.types.Scores",
               "value":{
                  "scoreHeader":{
                     "customScoreName":null,
                     "scoreName":"text"
                  },
                  "score":{
                     "customName":"text",
                     "scoreName":"text"
                  }
               },
               "nil":false,
               "globalScope":false,
               "typeSubstituted":false
            }
         }
      ]
   }
}

和ScoreSupplement类:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ScoreSupplement", propOrder = {
    "scoreHeader",
    "score"
})
public class ScoreSupplement {

    @XmlElement(required = true)
    protected SupplementHeader scoreHeader;
    protected Score score;

    //getters and setters
}

第二等:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Scores", propOrder = {
    "customs"
})
public class Scores {

    @XmlElementRefs({
        @XmlElementRef(name = "risc", type = JAXBElement.class, required = false)
    })
    protected List<JAXBElement<ScoreSupplement>> customs;

    //getters and setters
}

我检查了调试器,甚至没有输入适配器代码。 有没有人遇到过类似的问题并以某种方式解决了该问题?

0 个答案:

没有答案