Search code examples
stringactionscript-3apache-flexdatagridflex4.5

Can I convert a JSON string to a Flex ArrayCollection in without changing the item order?


Regarding this issue, I have generated dynamically string from Java .each time string format change , for example String format is

[{"BranchName":"Corporate Office","Date":"08\/03\/2013","SPName":"Pharmacy","SPAmount_5-00%":"100.00","SPVATAmount_5-00%":"15.00","SPOtherCharges_5-00%":"30.00","SPAmount_14-50%":"200.00","SPVATAmount_14-50%":"39.00","SPOtherCharges_14-50%":"71.00","SPColTPA":"100.00","SPColChequeDD":"50.00","SPHdfcCC":"100.00","SPIdbiCC":"100.00","SPColCash":"50.00","Difference":"55.00"},

But when I convert array collection with following code .

var rawData:String = String(event.result); 
var arr:Array = (JSON.decode(rawData) as Array);
var dp:ArrayCollection = new ArrayCollection(arr);

but array collection order changed as default sort like [Branch, Date, Difference,.. ] . But I want same as string format order. So How can I prevent Default order.


Solution

  • Actually, what you've described here is an array of objects (your example just includes one object). In the JSON parsing to array, each object is indeed in the order in which it is declared; but in the OBJECTS that are created, the properties may not be listed in the same order.

    For example:

    '[ {"Branch":"Corporate", "Department":"Finance", "Cost":"10000", "Attended":"true"},' +
    '{"Branch":"Las Vegas", "Department":"Hospitality", "Cost":"20100", "Attended":"false"},' +
    '{"Branch":"San Diego", "Department":"Banking", "Cost":"11023", "Attended":"true"}]'
    

    Parsing would return arr[0] as the Corporate object, arr[1] as the Las Vegas object, etc. Iterating through the properties I got:

    var obj:Object = dp.getItemAt(0);
    for (var prop:String in obj) {
        trace(prop + ' is ' + obj[prop]);
    }
    
    Department is Finance
    Attended is true
    Branch is Corporate
    Cost is 10000