0
votes

The Sencha Touch web app loads a store from JSON submitted by REST web services. For other technical requirements, the JSON is not standard (but still valid) and follows this pattern:

{
    "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"
    }
}

Unfortunately, when I do a myStore.load(), ST cannot pars the JSON and the data isn't added to the store. But if the JSON response would follow the following pattern, it would work:

 [
    {
        "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"
    }
]

I can't change the format of the JSON, so I need to find a way to get it work with this response. Is it possible to add parameters to the JSON reader of ST or is it possible to manually parse the JSON response ? If yes, how ?

Here is the proxy of my store :

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

1 Answers

1
votes

You can create a custom reader:

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; 
    }
});

by customizing parseResponse you can handle the data the way you want.