【问题标题】:Grouping jsonObjects in an jsonArray Android在 jsonArray Android 中对 jsonObjects 进行分组
【发布时间】:2017-09-06 13:21:45
【问题描述】:

我有一个带有一堆 jsonObjects 的 jsonArray,我想通过 market_id 对它们进行分组,这样具有相似 market_id 的对象将分别保存在它们自己的列表或数组中。我怎样才能做到这一点?

[
{
    "product_id": "12301",
    "selection": "No",
    "sales": "31",
    "market_id": "10",
},
{
    "product_id": "12302",
    "selection": "No",
    "sales": "24",
    "market_id": "43",
},
{
    "product_id": "12303",
    "selection": "Yes",
    "sales": "121",
    "market_id": "10",
},
{
    "product_id": "12304",
    "selection": "No",
    "sales": "0",
    "market_id": "43",
},
{
    "product_id": "12305",
    "selection": "Yes",
    "sales": "20",
    "market_id": "43",
},

]

为了达到这样的目的:

[{
    "product_id": "12304",
    "selection": "No",
    "sales": "0",
    "market_id": "43",
},
{
    "product_id": "12305",
    "selection": "Yes",
    "sales": "20",
    "market_id": "43",
},
{
    "product_id": "12302",
    "selection": "No",
    "sales": "24",
    "market_id": "43",
},]

【问题讨论】:

  • 我认为您应该先检查 id 根据您制作的具有相似 id 的 json 数组
  • 到目前为止您尝试过什么?显示您的代码。
  • @Bmbariah 如果您按market_id 分组,那么您的product_id 呢?看起来您在 JSON 中的 product_id 对于每个 market_id 都是不同的。
  • @NikhilSharma 谢谢..您的建议有效。我想我一直在寻找类似比较器或集合的东西,而忽略了基础

标签: android arrays json sorting


【解决方案1】:

首先创建一个实现 Comparator 接口的 Product 模型类,以便您对 ProductList 进行排序,在本例中按 marketId

Product.java

public class Product implements Comparator<Product> {
public String productId;
public String selection;
public String sales;
public String marketId;

public Product() {
    super();
}

@Override
public int compare(final Product p1, final Product p2) {
    if (!TextUtils.isEmpty(p1.marketId) && !TextUtils.isEmpty(p2.marketId)) {
        return p1.marketId.compareTo(p2.marketId); //Ascending order
    }
    return 0;
}
}

其次,创建一个产品解析器类,将您的产品列表 JSONArray 解析为产品类型列表,并将产品类型列表解析为分组的产品 JSONArray。

ProductParser.java

public class ProductParser {
private static final String TAG = ProductParser.class.getSimpleName();
private static final String PRODUCT_ID = "product_id";
private static final String SELECTION = "selection";
private static final String SALES = "sales";
private static final String MARKET_ID = "market_id";
private static final String HELPER_ID = "-1";

public ProductParser() {
    super();
}

public List<Product> parseProductArrayToProductList(final JSONArray productArray) {
    final List<Product> productsList = new ArrayList<>();
    if (null != productArray) {
        try {
            final int productCount = productArray.length();
            for (int i = 0; i < productCount; ++i) {
                final JSONObject productJson = productArray.getJSONObject(i);
                final Product product = new Product();
                product.productId = productJson.getString(PRODUCT_ID);
                product.selection = productJson.getString(SELECTION);
                product.sales = productJson.getString(SALES);
                product.marketId = productJson.getString(MARKET_ID);
                productsList.add(product);
            }
        } catch (final JSONException e) {
            Log.e(TAG, e.toString());
        }
    }
    return productsList;
}

public JSONArray parseProductListToGroupedProductArray(final List<Product> productList) {
    final JSONArray groupedProductArray = new JSONArray();
    if (null != productList && !productList.isEmpty()) {
        final int productCount = productList.size();
        String currentMarketId = HELPER_ID;
        JSONArray productArray = null;
        for (int i = 0; i < productCount; ++i) {
            final Product product = productList.get(i);
            if (null != product) {
                if (!currentMarketId.equals(product.marketId)) {
                    currentMarketId = product.marketId;
                    if (null != productArray) {
                        groupedProductArray.put(productArray);
                    }
                    productArray = new JSONArray();
                }
                try {
                    final JSONObject productObject = new JSONObject();
                    productObject.put(PRODUCT_ID, product.productId);
                    productObject.put(SELECTION, product.selection);
                    productObject.put(SALES, product.sales);
                    productObject.put(MARKET_ID, product.marketId);
                    productArray.put(productObject);
                } catch (final JSONException e) {
                    Log.e(TAG, e.toString());
                }
            }
        }
        if (null != productArray) {
            groupedProductArray.put(productArray);
        }
    }
    return groupedProductArray;
}
}

最后,在您的活动中或您需要实现此功能的任何地方,使用提供的类。

MainActivity.java

public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();

@Override
protected void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final String data = "\r\n\r\n[\r\n   {\r\n      \"product_id\": \"12301\",\r\n      \"selection\": \"No\",\r\n      \"sales\": \"31\",\r\n      \"market_id\": \"10\"\r\n   },\r\n   {\r\n      \"product_id\": \"12302\",\r\n      \"selection\": \"No\",\r\n      \"sales\": \"24\",\r\n      \"market_id\": \"43\"\r\n   },\r\n   {\r\n      \"product_id\": \"12303\",\r\n      \"selection\": \"Yes\",\r\n      \"sales\": \"121\",\r\n      \"market_id\": \"10\"\r\n   },\r\n   {\r\n      \"product_id\": \"12304\",\r\n      \"selection\": \"No\",\r\n      \"sales\": \"0\",\r\n      \"market_id\": \"43\"\r\n   },\r\n   {\r\n      \"product_id\": \"12305\",\r\n      \"selection\": \"Yes\",\r\n      \"sales\": \"20\",\r\n      \"market_id\": \"43\"\r\n   }\r\n]\r\n\r\n";
    final List<Product> productList = getProductList(data);
    Collections.sort(productList, new Product());
    final JSONArray sortedProductArray = getProductArray(productList);
    Log.e(TAG, sortedProductArray.toString()); // Here you have!
}

private List<Product> getProductList(final String data) {
    List<Product> productList = new ArrayList<>();
    try {
        final JSONArray productArray = new JSONArray(data);
        final ProductParser parser = new ProductParser();
        productList = parser.parseProductArrayToProductList(productArray);
    } catch (final JSONException e) {
        Log.e(TAG, e.toString());
    }
    return productList;
}

private JSONArray getProductArray(final List<Product> productList) {
    final ProductParser parser = new ProductParser();
    return parser.parseProductListToGroupedProductArray(productList);
}
}

【讨论】:

    【解决方案2】:

    我最终只是简单地遍历了 jsonArray 中的每个对象,并将共享相似 market_id 的对象添加到它们自己的 jsonArray 中。它不漂亮,但很有效。

      try {
    
            JSONArray jsonArray = new JSONArray(mainjson);
    
            for (int i = 0; i < jsonArray.length(); i++) {
    
                JSONObject jsonObject = jsonArray.getJSONObject(i);
    
                String market_id = jsonObject.getString("market_id");
    
                if (market_id.equalsIgnoreCase("43")) {
    
                    JSONObject json = new JSONObject();
                    json.put("match_id", jsonObject.getString("product_id"));
                    json.put("selection", jsonObject.getString("selection"));
                    json.put("sales", jsonObject.getString("sales"));
                    json.put("market_id", jsonObject.getString("market_id"));
                    new_json.put(json);
    
                } else if (market_id.equalsIgnoreCase("10")) {
                  ....
    

    【讨论】:

    • 等一下,我会给你一个优雅的解决方案
    • 谢谢!让我测试一下。
    • 让我知道它是否有效,我已经测试过并且看起来效果很好
    猜你喜欢
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    相关资源
    最近更新 更多