Search code examples
jsonscalajson4s

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.

I want to override the toString method of the class to give a json-string just like javascript's json.stringify() does.

Is this possible with 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. And i remember reading some-where not to use case classes if i want mutable members.

Thanks,


Solution

  • You can make a custom serialiser for your class as it is described in here: 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; I'd rather advice to have some other object perform the transformation as it will make things a bit tidier and easier to manage.