Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
1  
which JSon library you are using? Those details will be helpful in answering your question quickly. –  Nambari Dec 31 '11 at 17:37
    
Edited with details. –  shady2020 Dec 31 '11 at 18:21
add comment

3 Answers

up vote 0 down vote accepted

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 );
share|improve this answer
    
This answered my question the best.Though I have went with just using normal shared preferences for my purposes.I had wanted to implement a simple high score system.I figured this could be done storing the scores and details in a single string in shared preferences and then parsing it during retrival. –  shady2020 Jan 1 '12 at 8:46
    
You certainly can write json strings into shared preferences just as you wished using this method above. Using JSON libs is essentially the same amount of code as writing directly to shared prefs. It's still roughly the same translation code to translate your objects from your model to JSON or shared prefs. –  chubbsondubs Jan 1 '12 at 15:42
add comment

I've used Google's gson library to do this in the past. See here: http://code.google.com/p/google-gson/

share|improve this answer
add comment

I'm assuming your JSON array contains multiple instances of the same primitive type (string, int, float etc. - if not then you're going to have problems).

In which case you need to do something like this (assuming an array of strings):

String[] strArray = new String[jsonArray.length()];

for (int i = 0; i < jsonArray.length(); i++) {
    strArray[i] = jsonArray.getString(i);
}

Obviously if you are dealing with other primitive types make the appropriate substitutions.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.