Sunday, 15 May 2011

java - Generalizing field names with Gson -



java - Generalizing field names with Gson -

i have json objext looks this:

{ "isdefault": false, "someindex": [ 0 ], "label": "hello", "valuekindname": "someid", "value": 3, "conditions": { "salestype": [ 1, 2 ], "producttype": [ 1, 5 ] } }

now conditions class looks this:

public class conditions { private list<integer> salestype = new arraylist<integer>(); private list<integer> producttype = new arraylist<integer>(); }

this works. want generalize class new type conditions like:

"exampletype": [ 6, 9 ]

without having add together

private list<integer> exampletype = new arraylist<integer>();

to conditions.class.

i have thought of following:

public class conditions { private arraylist<condition> conditions = new arraylist<condition>(); }

and

public class status { private string key; private arraylist<integer> values; }

but gson of course of study doesn't know how convert json type of info structure.

any help highly apprectiated :)

you can register own converter. little this:

public class conditionconverter implements jsonserializer<condition>, jsondeserializer<condition> { @override public jsonelement serialize(condition src, type typeofsrc, jsonserializationcontext context) { final jsonobject cond = new jsonobject() cond.add(src.key, context.serialise(src.values); homecoming cond; } public status deserialize(jsonelement json, type typeoft, jsondeserializationcontext context) throws jsonparseexception { // pick apart , create status 1 time again } }

you register type adapter gsonbuilder:

builder.registertypeadapter(condition.class, new conditionconverter());

to pick apart object, you'll need utilize jsonobject.entryset(), don't know key name beforehand. job easier if adopted json this:

{ key: "exampletype", values: [ 42, 43 ] }

java android json gson

No comments:

Post a Comment