JSON.encode
and JSON.decode
are that, what you are looking for, but they are work good with primitive types (be careful, for example DateTime - is not primitive) and collections of primitive types. So if you want to do it for object, you should convert it to map/from map. Conversion to map can be called automatically when object is passed to JSON.encode
, if this object has method Map toJson()
, conversion from map should be done explicitly (for example, with constructor with Map
parameter).
Also, that can be useful: I prefer to avoid implicit toJson
call, cause when it throws exception, you will not see its message and call stack in this case.
Useful links and some info about this can be found in this question.