【问题标题】:Converting JSONArray to normal Array将 JSONArray 转换为普通数组
【发布时间】:2012-01-31 03:30:44
【问题描述】:

我从用户定义对象的普通数组创建了一个 JSON 数组。如何将 JSONArray 转换回用户定义类型的普通数组..? 我在 android 中使用 Json 来共享偏好。使用我在网上找到的这段代码:

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

我正在尝试将用户定义的对象数组转换为 jsonarray 并将其存储在 jsonshared 首选项中,然后尝试检索它。知道如何检索它时遇到问题。 谢谢。

【问题讨论】:

  • 您使用的是哪个 JSon 库?这些详细信息将有助于快速回答您的问题。

标签: android json sharedpreferences arrays


【解决方案1】:

我假设您的 JSON 数组包含相同原始类型(字符串、整数、浮点等)的多个实例 - 如果不是,那么您将遇到问题。

在这种情况下你需要做这样的事情(假设一个字符串数组):

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

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

显然,如果您正在处理其他原始类型,请进行适当的替换。

【讨论】:

    【解决方案2】:

    我过去曾使用 Google 的 gson 库来执行此操作。看这里: http://code.google.com/p/google-gson/

    【讨论】:

      【解决方案3】:

      如果您使用的是 Android 附带的 JSONObject,那么从用户定义的类型转换为 JSONObject/JSONArray 然后再转换回来会很繁琐。还有其他库会自动执行此转换,因此只需一两行即可对 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();
      

      这都可以封装在 ProductLineItem.toJSON() 中。解析类似。我喜欢创建一个构造函数,它接受一个 JSONObject 并创建如下对象: 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");
         }
      }
      

      处理数组非常相似。所以像:

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

      你可以看到这个样板代码对于一个简单的 2 个对象是非常重要的。所以你可以继续这样做,或者你可以使用一个库来为你处理所有这些:

      http://flexjson.sourceforge.net

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

      【讨论】:

      • 这最好地回答了我的问题。虽然我只是使用普通的共享偏好来实现我的目的。我想实现一个简单的高分系统。我认为这可以存储分数和共享首选项中单个字符串中的详细信息,然后在检索期间对其进行解析。
      • 您当然可以使用上述方法将 json 字符串写入共享首选项中。使用 JSON 库本质上与直接写入共享首选项的代码量相同。将对象从模型转换为 JSON 或共享首选项的翻译代码仍然大致相同。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-10
      • 2018-08-20
      • 2015-02-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多