【问题标题】:How to convert JSON to HashMap and compare them?如何将 JSON 转换为 HashMap 并进行比较?
【发布时间】:2023-03-30 01:40:02
【问题描述】:

我有一个像这样存储在数据库中的 json,

"supported_iso_codes":[
 {
      "EUR": "978",
      "USD": "840"
    }

],

要在我的应用程序代码中访问它,我会这样做......

getISOProfileDB.getSupportedISOCodes();

我有一个用户输入的字符串(提供欧元、美元等输入字符串)。如何将上述 json 转换为 HashMap 并将其与另一个字符串进行比较?我想要实现的是,

  1. 将 json 的关键部分与用户输入字符串 (EUR) 进行比较。
  2. 如果两者都匹配,则
  3. 解析json的value部分,保存到变量中。

以下是我想要实现的目标,

   tran.setCurrency(hashMapOfJson.get(currencyString));

【问题讨论】:

    标签: java android json hashmap gson


    【解决方案1】:

    使用 Gson :

    dependencies {
        compile 'com.google.code.gson:gson:2.2.4'
    }
    

    然后:

    Map<String, Object> supported_iso_codes = new Gson().fromJson(getISOProfileDB.getSupportedISOCodes(), new TypeToken<HashMap<String, Object>>() {}.getType());
    

    【讨论】:

      【解决方案2】:

      你可以这样做

              Gson gson = new Gson();
              Type type = new TypeToken<List<Map<String, String>>>(){}.getType();
              final ArrayList<HashMap<String,String>> isoCodesMapList = gson.fromJson(data, type);
              System.out.println(arrayList);
      

      那么为了让用户选择货币,你可以这样做

      isoCodesMapList.get(userSelectedCurrency);
      

      希望这会有所帮助:)

      【讨论】:

        【解决方案3】:

        您应该考虑使用 JSONObject (Jsonobject.org) 或 Gson。

        【讨论】:

        • 您的答案将通过提供与 OP 代码相关的示例来改进。就目前而言,您的“答案”与其说是解决方案,不如说是评论。
        猜你喜欢
        • 2019-02-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-06
        • 1970-01-01
        • 2015-01-30
        • 2018-02-14
        • 2013-06-09
        相关资源
        最近更新 更多