Reputation: 808
I would like to create a generic class which create my jsonObject. Is it possible to create a class which can create differents kind of objects like
{"chunkSize":10,"filters"
[{"field":"segmentOwners.id","operator":"EQUAL","value":"11578","valueType":"java.lang.Integer"},
{"field":"language","operator":"EQUAL","value":"FR","valueType":"java.lang.String"},
{"field":"customerId","operator":"EQUAL","value":"77","valueType":"java.lang.Integer"}]
,"orderBy":[{"field":"creationTime","order":"DESC"}],"page":0}
OR just a simple request:
{login:"mylogin",pwd:"mypwd"}
I tried something like:
@Override
protected JSONObject doInBackground(String... params) {
byte[] result = null;
Iterator iter = mData.entrySet().iterator();
JSONObject jsonObj = new JSONObject();
Iterator it = mData.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
try {
jsonObj.put((String) pairs.getKey(), (String) pairs.getValue());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
it.remove(); // avoids a ConcurrentModificationException
}
But i'm not sure that is the same kind of hashmap (string, jsonObjet...?)
Upvotes: 0
Views: 86
Reputation: 75629
I'd create generic container class (i.e. DataContainer
) which would expose unified API no matter of what data it holds (i.e. setFromJson()
, getData()
). Then create separate object for each data structure (i.e. DataLogin
, DataSomething
). Then when you fetch your json data from remote source, you could i.e. create DataLogin
object and hand it to your DataContainer
(or pass json to DataContainer so it could detect DataLogin
should be used and create it itself, but that require some logic which may not be best approach). Then all methods that are expected to work on your json data can be handed DataContainer object and method could do getType()
on it (you need to set type yourself of course), which would return what data is stored and then getData()
to get the data iself to work on.
Upvotes: 0
Reputation: 18670
If you want to create instances of JSONObject
from JSON strings, just do the following:
JSONObject jsonObj = new JSONObject("<your json string>");
Upvotes: 1