Encoding user objects to JSON with jyson.

If you wish to encode objects that not standard jython types, but are still representable in JSON, then you can control the JSON generation process by implementing a

__json__()
method on your objects. If you do so, then this method will be invoked by jyson at JSON generation time, and your method should return the JSON corresponding to your object. The return JSON text is not checked for correctness: that is your responsiblity. Here is some sample code.

You should always take care to return unicode strings from your method.

from com.xhaus.jyson import JysonCodec as json

class MyTestClass:

    def __init__(self):
        self.i = -1
        self.f = -2.0
        self.s = 'hi'

    def __json__(self):
        return u"""{"i":%d, "f":%lf, "s":"%s"}""" % (abs(self.i), abs(self.f), self.s.upper())

mtc = MyTestClass()
print json.dumps(mtc)

Which outputs

{"i":1, "f":2.000000, "s":"HI"}
Add picture from clipboard (Maximum size: 10 MB)