简体   繁体   English

使用json4s将scala对象转换为json

[英]convert scala object to json using json4s

I have an ordinary scala class not a case class with many member variables including Buffers, Lists etc. 我有一个普通的scala类而不是一个包含许多成员变量的case类,包括Buffers,Lists等。

I want to override the toString method of the class to give a json-string just like javascript's json.stringify() does. 我想覆盖类的toString方法,以提供json-string,就像javascript的json.stringify()一样。

Is this possible with json4s? 这有可能与json4s? Because the only examples i have seen so far are for case classes. 因为到目前为止我见过的唯一例子是案例类。

If possible what happens to member variables which are empty for eg: an empty list? 如果可能的话,成员变量会发生什么变化,例如:空列表?

I don't think i can use case classes because i perform a lot of state change operations on the member variables using methods. 我不认为我可以使用case类,因为我使用方法对成员变量执行了很多状态更改操作。 And i remember reading some-where not to use case classes if i want mutable members. 我记得在某些地方阅读 - 如果我想要可变成员,不要使用案例类。

Thanks, 谢谢,

You can make a custom serialiser for your class as it is described in here: https://github.com/json4s/json4s#serializing-non-supported-types 您可以为此类创建自定义序列化程序,如下所述: https//github.com/json4s/json4s#serializing-non-supported-types

Unless you really need it I wouldn't advice to make it part of your toString though; 除非你真的需要它,否则我不建议让它成为你的toString一部分; I'd rather advice to have some other object perform the transformation as it will make things a bit tidier and easier to manage. 我宁愿建议让其他对象执行转换,因为它会使事情变得更整洁,更容易管理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM