I created a a JSON Array from a normal array of user defined object.How do i convert the JSONArray back to a normal array of the user-defined type..?
I’m using Json for shared preference in android.Using this code i found on the net:
import org.json.JSONObject;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Context;
import android.content.SharedPreferences;
public class JSONSharedPreferences {
private static final String PREFIX = "json";
public static void saveJSONObject(Context c, String prefName, String key, JSONObject object) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(JSONSharedPreferences.PREFIX+key, object.toString());
editor.commit();
}
public static void saveJSONArray(Context c, String prefName, String key, JSONArray array) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString(JSONSharedPreferences.PREFIX+key, array.toString());
editor.commit();
}
public static JSONObject loadJSONObject(Context c, String prefName, String key) throws JSONException {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
return new JSONObject(settings.getString(JSONSharedPreferences.PREFIX+key, "{}"));
}
public static JSONArray loadJSONArray(Context c, String prefName, String key) throws JSONException {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
return new JSONArray(settings.getString(JSONSharedPreferences.PREFIX+key, "[]"));
}
public static void remove(Context c, String prefName, String key) {
SharedPreferences settings = c.getSharedPreferences(prefName, 0);
if (settings.contains(JSONSharedPreferences.PREFIX+key)) {
SharedPreferences.Editor editor = settings.edit();
editor.remove(JSONSharedPreferences.PREFIX+key);
editor.commit();
}
}
}
I’m trying to convert a user defined object array into jsonarray and storing it in jsonshared preference and later trying to retrive it.Having problem knowing how to retrive it.
Thanks.
If you’re using JSONObject that comes with Android its tedious to convert from User defined types to JSONObject/JSONArray then back again. There are other libraries out there that will do this transformation automatically so it’s simple one or two line to decode/encode JSON.
This could all be encapsulated within ProductLineItem.toJSON(). Parsing is similar. I like to create a constructor that takes a JSONObject and creates the object like: ProductLineItem obj = new ProductLineItem( jsonObject ):
Handling arrays is very much the same. So something like:
You can see just for a simple 2 objects this boiler plate code is quite significant. So you can continue to do this or you can use a library that handles all of this for you:
http://flexjson.sourceforge.net