问题描述
我的Scala类中有一个ArrayBuffer(如果使用Java,则有点像ArrayList).以下是我的代码:
I have an ArrayBuffer in my Scala class (somewhat like a ArrayList if using Java). The following is my code:
class MyClass {
val names: ArrayBuffer[Name] = new ArrayBuffer[Name]
var phone: String = null;
def toJsonString(): String = {
return (new GsonBuilder().serializeNulls().create()).toJson(this);
}
override def toString(): String = {
return toJsonString();
}
}
然后,当我尝试打印MyClass对象时:
Then when I try to print my MyClass object:
var myObj = new MyClass
val name = new Name()
name.setFirstName("John")
name.setLastName("Smith")
myObj.names.append(name)
println(myObj.toString())
然后我的输出如下:
Then my output looks like:
{"names":{"initialSize":16,"array":[{"firstName":"John","middleName":null,"lastName":"Smith"},null,null,null,null,null,n
ull,null,null,null,null,null,null,null,null,null],"size0":1},"phone":null}
有没有一种方法可以使输出JSON如下所示?也许使用除ArrayBuffer以外的其他集合?谢谢!
Is there a way I can make the output JSON like below? Perhaps using a different collection other than ArrayBuffer? Thanks!
{"names":[{"firstName":"John","middleName":null,"lastName":"Smith"}],"phone":null}
推荐答案
您有很多不错的选择(例如,使用另一个序列化库代替Gson,使用不可变集合等),但这是使用最小代码的解决方案更改:
You have many good options (e.g. use another serialization library instead of Gson, use an immutable collection etc.), but here's a solution with minimal code changes:
为ArrayBuffer添加一个自定义序列化器,将其转换为不可变的Array
,从而摆脱空单元格:
Add a custom serializer for ArrayBuffer that converts it to an immutable Array
, thus getting rid of the empty cells:
import com.google.gson._
import scala.reflect.ClassTag
import java.lang.reflect.Type
class ArrayBufferSerializer[T : ClassTag] extends JsonSerializer[ArrayBuffer[T]] {
override def serialize(src: ArrayBuffer[T], typeOfSrc: Type, context: JsonSerializationContext): JsonElement = {
context.serialize(src.toArray)
}
}
然后在MyClass.toJsonString
的GsonBuilder中注册它:
Then register it in the GsonBuilder in MyClass.toJsonString
:
def toJsonString(): String = {
new GsonBuilder()
.registerTypeAdapter(classOf[ArrayBuffer[Name]], new ArrayBufferSerializer[Name]())
.serializeNulls()
.create()
.toJson(this)
}
这会产生您想要的结果:
This produces the result you're looking for:
{"names":[{"firstName":"John","middleName":null,"lastName":"Smith"}],"phone":null}
这篇关于Scala:ArrayBuffer/ArrayList的Json表示...如何避免在集合中打印出空信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!