【问题标题】:JsonArray to List in AndroidJsonArray 在 Android 中列出
【发布时间】:2015-09-22 15:39:15
【问题描述】:

假设我有一个 JsonValue 执行以下操作:

    private async Task<JsonValue> fetchCheeseAsync (string url)
    {
        HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (new Uri (url));
        request.ContentType = "application/json";
        request.Method = "GET";

        using (WebResponse response = await request.GetResponseAsync ()) {
            using (Stream stream = response.GetResponseStream ()) {
                JsonValue jsonDoc = await Task.Run (() => JsonObject.Load (stream));
                Console.WriteLine ("Response: {0}", jsonDoc.ToString ());
                return jsonDoc;
            }
        }
    }

jsonDoc 的类型是JsonArray,它看起来像这样:

[
  {
    "cheese": [
      "American"
    ]
  },
  {
    "cheese": [
      "Asiago"
    ]
  },
  {
    "cheese": [
      "Feta",
      "Cheddar"
    ]
  },
  {
    "cheese": [
      "Goat",
      "Asiago",
      "American"
    ]
  }
]

这只是一个示例,但实际文件很大。 所以我的最终目标是列出奶酪的类型并找出它们的使用次数。

所以在本例中,American 使用了两次,Asiago 使用了两次,但 FetaCheddarGoat 使用了一次。

如何将此JsonArray 转换为List

【问题讨论】:

    标签: android arrays json list xamarin


    【解决方案1】:

    嗯,这是可以用来从奶酪数组中获取值的东西,由你来决定当奶酪数据真正出现时要做什么。

    String result = jsonString;
    List<cheese> cheeseList = new ArrayList<>();
    try {
        JSONArray jsonArray = new JSONArray(result);
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            JSONArray jsonArray1 = jsonObject.getJSONArray("cheese");
            for (int n = 0; n < jsonArray1.length(); n++) {
                String cheese = jsonArray1.getString(i);
                //here you kind of do whatever you want with it
                cheese cheese = new Cheese();
                cheese.dfas = cheese;
                cheeseList.add(cheese);
            }
        }
    } catch (JSONException e) {
        Toast.makeText(mContext, "Error getting cheese Info", Toast.LENGTH_SHORT).show();
        LogUtils.LOGI(TAG, e.toString());
    }
    

    【讨论】:

      猜你喜欢
      • 2014-02-10
      • 1970-01-01
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-15
      • 1970-01-01
      相关资源
      最近更新 更多