Categories
discuss

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….

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.

Answer

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 );
Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..