ambiguous reference to overloaded definition, both method toJSONString in class JSON of type (x$1: A


问题:在scala中将对象转为json字符串时,经常会出现这样的问题

  unionDS.print()
    unionDS.map(x=> JSON.toJSONString(x))
        .addSink(MyKafkaUtil.getKafkaProducer(sinkTopic))

错误信息:

Error:(100, 26) ambiguous reference to overloaded definition,
both method toJSONString in class JSON of type (x$1: Any, x$2: com.alibaba.fastjson.serializer.SerializerFeature*)String
and  method toJSONString in class JSON of type (x$1: Any)String
match argument types (com.alibaba.fastjson.JSONObject)
    unionDS.map(x=> JSON.toJSONString(x))

原因:

重载的方法有多个,不知道选择哪一个。

解决方法:

方法一:

 unionDS.print()
    unionDS.map(x=> JSON.toJSON(x).toString)

方法二:

    unionDS.print()
    unionDS.map(x=> JSON.toJSONString(x,SerializerFeature.PrettyFormat))