简体   繁体   English

从哈希数组创建JSONArray

[英]Create JSONArray from array of hash

I have a Array of hash like this 我有这样的哈希数组

[
  {"id":"1","name":"Apple","category":"fruit"},
  {"id":"2","name":"Ball","category":"toy"},
  {"id":"3","name":"Cat","category":"animal"},
  ..
  ..
  {"id":"500","name":"yoyo","category":"toy"},
  ..
]

I have a method which accepts JsonArray . 我有一个接受JsonArray的方法。 How can I pass this, so that later I can search a particular type of category like toy and return its index? 如何传递此密码,以便以后可以搜索特定类型的类别(例如toy并返回其索引?

Since this contains quotes, so I can't even figure out how to directly pass this as a new JsonArray(). 由于它包含引号,所以我什至无法弄清楚如何直接将其作为新的JsonArray()传递。

Convert your JSON string into a JSONArray object like this 像这样将JSON字符串转换为JSONArray对象

JSONArray jsonArray = new JSONArray(jsonString);

Use the method to find all indexes of specific category 使用该方法查找特定类别的所有索引

public List<Integer> getIndexesOfCategory(JSONArray jsonArray,String category) {
        List<Integer> indexes = new ArrayList<>();

        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            if (category.equals(jsonObject.getString("category"))) {
                indexes.add(i);
            }
        }
        return indexes;
    }

Use like this 这样使用

List<Integer> indexes = getIndexesOfCategory(jsonArray,"toy") ; List<Integer> indexes = getIndexesOfCategory(jsonArray,"toy") ;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM