简体   繁体   中英

parsing JS (with functions) using GSON

I have a bunch of files containing Javascript, which store configuration metadata, and I'd like to use GSON (2.2.4) to parse them into Java objects to be read by my application. This works for simple name/value pairs, but if my JS file has a function, of course GSON throws an exception:

[
    {
        text:'Cost',
        renderer:function(value)
        { 
           return 0; 
        }   

    },  ...

com.google.gson.stream.MalformedJsonException: Expected ':' at line 4 column 38

I'm wondering if there's any way to have GSON parse this type of JS file, even if it has to completely ignore functions and just parse the simple name/value pairs? I guess I'd need to do some preprocessing on the input?

Technically, functions are not a data type which is represented by the JSON format in the spec , those are rather:

string number object array true false and null

In practice, a lot of JSON parsers will ignore functions while serializing a JSON object, like the Javascript version as implemented by many browsers :

If undefined, a function, or an XML value is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array).

So, I don't know how you are receiving the JSON, but serializing it correctly is the best solution and it is usually the easiest, if you can.

If you don't have control over the JSON you are receiving, then GSON gives you the possibility of defining custom deserializers , which should make you be able to actually parse the JSON you have correctly and without throwing exceptions. But it will require a little amount of work, obviously.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM