rokucommunity / brighterscript

A superset of Roku's BrightScript language
MIT License
152 stars 47 forks source link

How to FormatJson() of BrighterScript object #1077

Closed vovan888 closed 2 months ago

vovan888 commented 4 months ago

Consider the following example. Running it results in TestClassJson = "".

class TestClass
    public name as string

    public function walk()
        print "walk"
    end function
end class

    TestClassInstance = new TestClass()
    TestClassInstance.name = "TestClassInstance"
    TestClassInstance.walk()
    TestClassJson = FormatJson(TestClassInstance)
TwitchBronBron commented 2 months ago

When I run your example, I get this error in the console: image

BrightScript refuses to serialize object that have non-serializable properties on them.

When I eliminate the methods, then it works.

TestClassInstance = new TestClass()
TestClassInstance.name = "TestClassInstance"
TestClassInstance.walk()
TestClassInstance.walk = invalid
TestClassInstance.new = invalid
TestClassJson = FormatJson(TestClassInstance)
print TestClassJson
{"name":"TestClassInstance","new":null,"walk":null}

So the quick answer is to delete all the methods from the classes.

This might be worth a brighterscript enhancement that adds a .ToJson() method to classes that strip out the non-serializable stuff.

TwitchBronBron commented 2 months ago

I just discovered an undocumented way of safely stripping out unsupported items. You should be able to do this:

TestClassInstance = new TestClass()
TestClassInstance.name = "TestClassInstance"
TestClassInstance.walk()
TestClassJson = FormatJson(TestClassInstance, 256) 'flag 256 sets all non-serializable items to to `null`
print TestClassJson
TwitchBronBron commented 2 months ago

I'm going to close this because it's more a problem with the platform than with brighterscript, and with the 256 flag you should be able to get what you want from it.