2011-12-31 25 views
5

Creé una matriz JSON a partir de una matriz normal de objetos definidos por el usuario. ¿Cómo convierto el JSONArray a una matriz normal del tipo definido por el usuario? estoy usando JSON para la preferencia compartida en android.Using este código he encontrado en la red:Conversión de JSONArray a la matriz normal

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(); 
     } 
    } 
} 

Estoy tratando de convertir una tabla de objeto definido por el usuario en JSONArray y almacenarla en la preferencia jsonshared y posteriormente tratando para recuperarlo. Tener problemas para saber cómo recuperarlo. Gracias.

+1

¿qué biblioteca JSon está utilizando? Esos detalles serán útiles para responder su pregunta rápidamente. – kosa

+0

Editado con detalles. – shady2020

Respuesta

0

Si está utilizando JSONObject que viene con Android, es tedioso convertir de tipos definidos por el usuario a JSONObject/JSONArray y viceversa. Hay otras bibliotecas por ahí que harán esta transformación automáticamente, por lo que es simple una o dos líneas para decodificar/codificar 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(); 

Todo esto podría estar encapsulado en ProductLineItem.toJSON(). El análisis es similar. Me gusta crear un constructor que toma un JSONObject y crea el objeto como: 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"); 
    } 
} 

Manejo de matrices es muy similar. Así que algo como:

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; 
    } 
} 

Usted puede ver sólo por un simple 2 objetos este código placa de la caldera es bastante significativo. Para que pueda seguir haciendo esto o puede utilizar una biblioteca que se encarga de todo esto para usted:

http://flexjson.sourceforge.net

// serialize 
String json = new JSONSerializer().serialize(shoppingCart); 
// deserialize 
ShoppingCart cart = new JSONDeserializer<ShoppingCart>().deserialize(json, ShoppingCart.class); 
+0

Esto respondió mejor a mi pregunta. Aunque he utilizado solo las preferencias compartidas normales para mis propósitos. Quisiera implementar un sistema simple de puntuación más alta. Pensé que esto se podía hacer almacenando los puntajes y los detalles en una sola cadena en compartida. preferencias y luego analizarlo durante la recuperación. – shady2020

+0

Ciertamente puede escribir cadenas json en las preferencias compartidas tal como deseaba utilizar este método más arriba. Usar JSON libs es esencialmente la misma cantidad de código que escribir directamente en las preferencias compartidas. Sigue siendo aproximadamente el mismo código de traducción para traducir sus objetos de su modelo a JSON o preferencias compartidas. – chubbsondubs

0

Estoy asumiendo que su matriz JSON contiene múltiples instancias del mismo tipo primitivo (cadena, int, float, etc - si no, entonces usted va a tener problemas).

En este caso usted tiene que hacer algo como esto (suponiendo una matriz de cadenas):

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

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

Obviamente, si se trata de otros tipos primitivos hacer las sustituciones apropiadas.

Cuestiones relacionadas