Thursday, 15 March 2012

gson - Sort json fields by field name -



gson - Sort json fields by field name -

i have json reply

{ "bfield":"some data", "afield":"some data", "cfield":"some data", "dfield":{ "b1field":"some data", "c1field":"some data", "a1field":"some data" } }

and want json, sorted field name

{ "afield":"some data", "bfield":"some data", "cfield":"some data", "dfield":{ "a1field":"some data", "b1field":"some data", "c1field":"some data" } }

i utilize gson on server create json, first question: can gson sort fields name? or tell me, pls, sites or javascript libaraies, can convert json json sorted name fields.

ps sorry bad english

updated: modify 'sortobject' function @dariogriffo sorting nested object fields:

function sortobject(o) { var sorted = {}, key, = []; (key in o) { if (o.hasownproperty(key)) { if (o[key]!=null && typeof o[key] === 'object'){ o[key] = sortobject(o[key]); } a.push(key); } } a.sort(); (key = 0; key < a.length; key++) { sorted[a[key]] = o[a[key]]; } homecoming sorted; };

now work me.

you can seek on javascript side

function sortobject(o) { var sorted = {}, key, = []; (key in o) { if (o.hasownproperty(key)) { a.push(key); } } a.sort(); (key = 0; key < a.length; key++) { sorted[a[key]] = o[a[key]]; } homecoming sorted; } var q = { bfield:'some data', afield:'some data', cfield:'some data', dfield:{ b1field:'some data', c1field:'some data', a1field:'some data' } }; var p = sortobject(q); console.log(p);

json gson

No comments:

Post a Comment