javascript - 如何正确使用 JsonUtils.safeEval() 中的 JSArray<T> 对象?

标签 javascript json gwt

我正在使用 RequestBuilder 读取静态 JSON 文件,并确认我在响应的 .getText() 方法中看到了预期的 JSON。我已经精简了我正在做的事情来尝试找出确切的问题。这就是我能做的最简单的事情了。

我使用 JsonUtils.safeEval() 将响应解析为我的覆盖类型,并将结果传递到一个函数中,该函数会将结果输出到页面上。显然,此方法还有更多内容,但为了简洁起见,我将其省略。

@Override
public void onResponseReceived(Request request, Response response) {    
    JsArray<JSONLeadTime> tmp = JsonUtils.<JsArray<JSONLeadTime>>safeEval(response.getText());
    if (200 == response.getStatusCode()) {
        renderLeadTimes(tmp);
    } else {
        AlertWindow.displayAlert(ERRORS.GENERIC_CLIENT_ERROR);      
    }
}

这里是覆盖类型定义,供引用。作为记录,还定义了“设备”覆盖类型。您可以从下面的 JSON 中收集定义,或者我可以根据需要添加该定义。

public class JSONLeadTime extends JavaScriptObject {
    protected JSONLeadTime() {}
    public final native String getFacility() /*-{ return this.facility; }-*/;
    public final native List<equipment> getEquipment() /*-{ return this.equipment; }-*/;
}

正在解析的 JSON 示例:

[{
    "JSONLeadTime": {
        "facility": "Temperance",
        "equipment": [{
            "name": "Coil Line",
            "value": "coil-line",
            "lead-time": 2,
            "sales-router-id": [76]
        }]
    }
}]

当我尝试迭代 JSArray 时,一切都很好,直到我尝试访问覆盖类型的方法。这是输出结果的方法。当我调用 LeadTimes.get(i) 时,我可以看到“leadTime”是一个 JavaScriptObject,这正是我当时所期望的。当我调用“leadTime.getFacility()”时,我得到了 NPE。

protected void renderLeadTimes(JsArray<JSONLeadTime> leadTimes) {
    SafeHtmlBuilder sb = new SafeHtmlBuilder();
    for (int i=0; i < leadTimes.length(); i++) {
        JSONLeadTime leadTime = leadTimes.get(i);
        sb.appendEscaped(leadTime.getFacility()); //This is where I get the NPE
        if ( leadTime.getEquipment() != null ) {
            for ( int  x=0; x < leadTime.getEquipment().size(); x++ ) {
                equipment e = leadTime.getEquipment().get(x);
                sb.appendEscaped(" - " + e.getName());
            }
        }
    }       
    view.getDivLeadTimes().setInnerSafeHtml(sb.toSafeHtml());
}

我彻底迷失了。我不知道为什么这不起作用。我读过的所有内容都表明这应该有效。任何尝试的想法将不胜感激。

最佳答案

您的 JSON 数组包含具有单个 JSONLeadTime 属性的对象,该属性的值将与您的叠加类型匹配。您缺少 JsArray 和覆盖类型之间的中间对象。

关于javascript - 如何正确使用 JsonUtils.safeEval() 中的 JSArray<T> 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56904244/

相关文章:

javascript - 使用 $httpBackend 和 $scope.$watch 对 Angular.js 进行单元测试

javascript - 键盘选择组合框中的 Extjs Quicktips

javascript - 如何从 Greasemonkey 脚本拦截 XMLHttpRequests?

javascript - json,如何检查 key ?

gwt - 尝试使用 gwt-cal 和 gwt-dnd 时出错

java - GWT 如何为每个浏览器(例如浏览器)提供正确的 Javascript 代码?进行i18n和浏览器兼容?

javascript - Angular.js 服务工厂模块...将内部代码作为函数返回?

java - 如何以JSON格式在couchbase lite android中插入数据

ios - 当值是带有 swiftyJSON 的 JSON 值时,如何获取 JSON 数据

gwt - GWT super 开发模式-bindAddress-更改未显示