Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting JSONArray to normal Array

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.

like image 405
shady2020 Avatar asked Nov 14 '22 12:11

shady2020


1 Answers

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.

ProductLineItem lineItem = ...;
JSONObject json = new JSONObject();
json.put( "name", lineItem.getName() );
json.put( "quantity", lineItem.getCount() );
json.put( "price", lineItem.getPrice() );
... // do this for each property in your user defined class
String jsonStr = json.toString();

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 ):

public class ProductLineItem {
    private String name;
    private int quantity;
    private float price;

   public MyObject( JSONObject json ) {
      name = json.getString("name");
      count = json.getInt("quantity");
      price = json.optFloat("price");
   }
}

Handling arrays is very much the same. So something like:

public class ShoppingCart {

     float totalPrice;
     List<Rebate> rebates = new ArrayList<Rebate>();
     List<ProductLineItem> lineItems = new ArrayList<ProductLineItem>();


    public ShoppingCart( JSONObject json ) {
        totalPrice = json.getFloat("totalPrice");

        for( JSONObject rebateJson : json.getArray("rebates") ) {
            rebates.add( new Rebate( rebateJson ) );
        }

        for( JSONObject productJson : json.getArray("lineItems") ) {
            lineItems.add( new ProductLineItem( productJson ) );
        }
    }

    public JSONObject toJSON() {
        JSONObject json = new JSONObject();
        json.put("totalPrice", totalPrice );

        JSONArray rebatesArray = new JSONArray();
        for( Rebate rebate : rebates ) {
            rebatesArray.put( rebate.toJSON() );
        }

        JSONArray lineItemsArray = new JSONArray();
        for( ProductLineItem lineItem : lineItems ) {
            lineItemsArray.put( lineItem.toJSON() );
        }

        json.put( "rebates", rebatesArray );
        json.put( "lineItems", lineItemsArray );

        return json;
    }
}

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

// serialize
String json = new JSONSerializer().serialize( shoppingCart );
// deserialize
ShoppingCart cart = new JSONDeserializer<ShoppingCart>().deserialize( json, ShoppingCart.class );
like image 70
chubbsondubs Avatar answered Nov 16 '22 02:11

chubbsondubs