在scala中需要将case class 序列化为string,代码如下
results.map(JSON.toJSONString(_)).foreach(println) case class pay(id:String)
然后出现下面的错误
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不知道调用哪个方法导致的
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是个枚举,我们直接选择第一个
results.map(JSON.toJSONString(_, SerializerFeature.QuoteFieldNames)).foreach(println)
但是出现的结果不是想要的,class的字段都没有序列化出来
{}
其实fastjson 默认是基于方法clz.getMethods()进行字段查找过滤的,而scala中的getter和setter方法完全不是java那种命名方式。scala中的getter:def foo():T setter: def foo_(val:T):Unit因此如果采用默认配置序列化scala对象,会出现如上问题。但是我们可以加上BeanProperty,目的是让这个类有getter和setter方法
case class pay(@BeanProperty id:String)
最后结果为
{"id":"1"}
另外我们还有一种基于Jackson的方式
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)