Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert scala object to json using json4s

Tags:

json

scala

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,

like image 606
Vikash Balasubramanian Avatar asked Jun 27 '26 00:06

Vikash Balasubramanian


1 Answers

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.

like image 88
Aldo Stracquadanio Avatar answered Jun 28 '26 17:06

Aldo Stracquadanio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!