【问题标题】:Sencha Touch 2 : Load non-standard JSON into storeSencha Touch 2 : 将非标准 JSON 加载到存储中
【发布时间】:2014-04-15 09:37:20
【问题描述】:

Sencha Touch Web 应用从 REST Web 服务提交的 JSON 加载商店。对于其他技术要求,JSON 不是标准的(但仍然有效)并遵循以下模式:

{
    "101": {
        "id": "101",
        "title": "title 101",
        "description": "description 101",
        "order": "20",
        "thumb": {
            "id": "10101",
            "uri": "http://linktothumb.jpg"
        },
        "parent": "0",
        "cType": "5"
    },
    "102": {
        "id": "102",
        "title": "title 102",
        "description": "description 102",
        "order": "59",
        "thumb": {
            "id": "10102",
            "uri": "http://linktothumb.jpg"
        },
        "parent": "101",
        "cType": "5"
    }
}

不幸的是,当我执行 myStore.load() 时,ST 无法解析 JSON,并且数据不会添加到存储中。但如果 JSON 响应遵循以下模式,它会起作用:

 [
    {
        "id": "101",
        "title": "title 101",
        "description": "description 101"
        "thumb": {
            "id": "10101",
            "uri": "http://linktothumb.jpg"
        },
        "parent": "0"
    },
    {
        "id": "102",
        "title": "title 102",
        "description": "description 102"
        "thumb": {
            "id": "10102",
            "uri": "http://linktothumb.jpg"
        },
        "parent": "101"
    }
]

我无法更改 JSON 的格式,所以我需要找到一种方法让它与这个响应一起工作。是否可以向 ST 的 JSON 阅读器添加参数,或者是否可以手动解析 JSON 响应?如果是,如何?

这是我商店的代理:

proxy: {
    type:'rest',
    useDefaultXhrHeader : false,
    headers: {
        'Accept': 'application/json'
    },
    reader: {
        type:'json'
    }
}

【问题讨论】:

    标签: json extjs sencha-touch sencha-touch-2


    【解决方案1】:

    您可以创建自定义阅读器:

    Ext.define("App.data.reader.MyReader", {
        extend: 'Ext.data.reader.Json',
        getResponseData: function(response) {
            var data, error;
    
            try {
                data = this.parseResponse(Ext.decode(response.responseText));             
                return this.readRecords(data)
            } catch (ex) {
                error = new Ext.data.ResultSet({
                    total  : 0,
                    count  : 0,
                    records: [],
                    success: false,
                    message: ex.message
                });
    
                this.fireEvent('exception', this, response, error);
                Ext.Logger.warn('Unable to parse the JSON returned by the server');
                return error;
            }
        },
        parseResponse: function(data) {
            return data; 
        }
    });
    

    通过自定义 parseResponse,您可以按照自己的方式处理数据。

    【讨论】:

    • 感谢您提供此解决方案。 parseResponse 函数应该返回哪种对象类型和结构来填充存储?
    • 查看错误情况,你必须返回一个这样的模板,其中记录是你要返回的单个模型的数组。
    猜你喜欢
    • 2012-07-24
    • 1970-01-01
    • 2012-06-12
    • 2012-01-15
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多