Platinum Partner
architects,html5,javascript,tips and tricks,extjs

ExtJs JSON Reader Example

I received the following email from a reader:

Thank you very much for finding time to read my mail.
It would be greatly helpful, if you could provide me with the code of binding the data dynamically to the DS. I have already generated the data in JSON format via Servlet:

{“success”:true,”campaignList”:[{"NumberOfCampaigns":1,"CamapaignScheduleDate":"Mar 23, 2013 12:00:00 AM"}]}

How do I attach this here..

var store = Ext.create(‘Ext.data.Store’, {
    model: ‘PopulationPoint’,
    data: MY_DATA
  });

Any help would be of great use.
Thanks and regards

Response:

There are a couple ways to approach this problem. The linked example that I wrote uses a raw Javascript object to render a pie chart. Lets say your servlet returns JSON in a variable – you could parse this yourself and use the result in the store, but Ext provides the JSONReader for this purpose:
var store = new Ext.data.JsonStore({
    url: '/servlet',
    root: 'campaignList',
    fields: [{name:'NumberOfCampaigns', type: 'int'},
             {name:'CampaignScheduleDate', type:'date'}]
});
A couple things to note here- this assumes you know the types in advance, and in particular, you want to test dates carefully to make sure you render them in a format Ext can parse.  If needed, you can specify a date format as well, like so: dateFormat: ‘m-d-Y g:i A’

You can add a “mapping” to the fields, to alias columns from the servlet. The root value is optional – if a servlet returns a raw array this is not necessary. You may need to add “totalProperty” to the store as well – this specifies the name of a property in the JSON payload which specifies the total number of records. This is only needed for paging scenarios, where not all the results are returned at once.



Published at DZone with permission of {{ articles[0].authors[0].realName }}, DZone MVB. (source)

Opinions expressed by DZone contributors are their own.

{{ tag }}, {{tag}},

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}