在scala中須要將case class 序列化爲string,代碼以下java
results.map(JSON.toJSONString(_)).foreach(println) case class pay(id:String)
而後出現下面的錯誤git
Error:(35, 12) ambiguous reference to overloaded definition, both method toJSONString in object JSON of type (x$1: Any, x$2: com.alibaba.fastjson.serializer.SerializerFeature*)String and method toJSONString in object JSON of type (x$1: Any)String match argument types (PayTest.this.pay) JSON.toJSONString(t)
查看FastJson toJSONString發現有個可變參數相同的方法,結合錯誤應該是scala不知道調用哪一個方法致使的github
public static final String toJSONString(Object object) { return toJSONString(object, new SerializerFeature[0]); } public static final String toJSONString(Object object, SerializerFeature... features) { SerializeWriter out = new SerializeWriter(); try { JSONSerializer serializer = new JSONSerializer(out); for (com.alibaba.fastjson.serializer.SerializerFeature feature : features) { serializer.config(feature, true); } serializer.write(object); return out.toString(); } finally { out.close(); } }
咱們直接在代碼指定調用可變參數的方法,SerializerFeature是個枚舉,咱們直接選擇第一個json
results.map(JSON.toJSONString(_, SerializerFeature.QuoteFieldNames)).foreach(println)
可是出現的結果不是想要的,class的字段都沒有序列化出來app
{}
其實fastjson 默認是基於方法clz.getMethods()進行字段查找過濾的,而scala中的getter和setter方法徹底不是java那種命名方式。scala中的getter:def foo():T setter: def foo_(val:T):Unit所以若是採用默認配置序列化scala對象,會出現如上問題。可是咱們能夠加上BeanProperty,目的是讓這個類有getter和setter方法ide
case class pay(@BeanProperty id:String)
最後結果爲this
{"id":"1"}
另外咱們還有一種基於Jackson的方式spa
def objectParse = new RichMapFunction[pay, String] { private var mapper: ObjectMapper = _ override def open(parameters: Configuration): Unit = { this.mapper = new ObjectMapper() } override def map(value: pay): String = { mapper.writeValueAsString(value) } } results.map(objectParse).foreach(println)