views:

342

answers:

3

I'm trying to serialize my business objects into JSON for consumption by a Javascript application. The problem is is that I'm trying to keep my business objects "pure" in the sense they are not aware of data access or persistence. It seems to me that "diluting" my objects with a toJSON() function would go against this goal. On the other hand, using an external object to serialize my business objects would not work since I keep all my instance variables private.

Am I approaching this totally the wrong way?

+5  A: 

If the instance variables are private, they should not appear in a serialization that is being sent to a JavaScript application. By definition, if you're serializing them and sending them to a separate application, they are public. So, an external object should have some way of accessing them, probably through some sort of getter methods.

Brian Campbell
A: 

What purpose does searializing the data in JSON serve? Is it purely for reporting? If so, then Brian is correct, those variables should have getter methods.

If the purpose of serialization is to transport the data to a JavaScript app where it can be manipulated and then returned to the originating application, then perhaps you would be best served by creating a related class that serves the purpose of serialization while still maintaining strong encapsulation.

For example, in Java you could define an inner class. An inner class instance has direct access to all fields of the enclosing class instance without the need of getter methods. Or you could group with a package (or namespace) using the correct access modifiers to permit access by the serializer, but not by any other class.

Or you could use reflection. Or hijack the toString method. (Or shine it all and create a toJson method.)

Benry
A: 

Are you thinking of generating JSON from non-javascript code (like server-side Java)? The answer kind of depends on that: handling of JSON is quite different on Javascript and, say, Java. There's already an answer wrt javascript-side, which seems correct.

If this is on Java, there are libraries that can help; for example (Jackson) can deserialize any bean, using regular getX/setX method introspection; plus additional (and optional) annotations.

StaxMan