简体   繁体   English

使用GSON解析JS(带有函数)

[英]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. 我有一堆包含Javascript的文件,这些文件存储配置元数据,我想使用GSON(2.2.4)将它们解析为Java对象,以供应用程序读取。 This works for simple name/value pairs, but if my JS file has a function, of course GSON throws an exception: 这适用于简单的名称/值对,但是如果我的JS文件具有功能,则GSON当然会引发异常:

[
    {
        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? 我想知道是否有办法让GSON解析这种类型的JS文件,即使它必须完全忽略函数并仅解析简单的名称/值对也是如此? 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: 从技术上讲,函数不是规范中 JSON格式表示的数据类型,而是:

string number object array true false and null string number object array true falsenull

In practice, a lot of JSON parsers will ignore functions while serializing a JSON object, like the Javascript version as implemented by many browsers : 实际上,许多JSON解析器在序列化JSON对象时会忽略函数,例如许多浏览器实现的Javascript版本:

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). 如果未定义,则在转换期间遇到函数或XML值时,将忽略它(在对象中找到它)或将其检查为空(在数组中找到它)。

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. 因此,我不知道您是如何接收JSON的,但是正确地对其进行序列化是最好的解决方案,并且如果可以的话,它通常是最简单的。

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. 如果您无法控制要接收的JSON ,则GSON允许您定义自定义反序列化器 ,这应该使您能够实际解析出您拥有的JSON,而不会引发异常。 But it will require a little amount of work, obviously. 显然,这将需要少量工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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