【问题标题】:How to create gson format for json map of date keys?如何为日期键的 json 映射创建 gson 格式?
【发布时间】:2019-08-29 09:59:13
【问题描述】:

我有问题,无法创建格式类以使用 gson 从文件中获取 json。

我的 json 看起来像:

{
  "2019-08-01": {
    "foo": [
      "2019-08-01 03:31:00Z",
      "2019-08-01 05:36:00Z"
    ],
    "baa": [
      "2019-08-01 05:36:00Z",
      "2019-08-01 13:27:00Z"
    ],
  }
}

而 kotlin 代码看起来是这样的:


class PFormat {
    val days: DateTimesFormat? = null
}

class DateTimesFormat {
    val dateTime: Map<String, List<String>>? = null
}

private var gson = Gson()

val pFormatJsonfile: File = File("/data/user/0/com.example.blabla/app_flutter/appSettings.json")
val bufferedReader: BufferedReader = prayersFormatJsonfile.bufferedReader()
val stringFromJsonFile = bufferedReader.use { it.readText() }
var pDataAsJson = gson.fromJson(stringFromJsonFile, PFormat::class.java)

print(pDataAsJson.days)

【问题讨论】:

  • 尝试使用 GsonBuilder().create() 创建 gson 对象。

标签: android json date kotlin gson


【解决方案1】:

此代码可能会有所帮助

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("yourfilename.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

像这样使用这个方法

try {
        JSONObject obj = new JSONObject(loadJSONFromAsset());
        JSONArray m_jArry = obj.getJSONArray("formules");
        ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> m_li;

        for (int i = 0; i < m_jArry.length(); i++) {
            JSONObject jo_inside = m_jArry.getJSONObject(i);
            Log.d("Details-->", jo_inside.getString("formule"));
            String formula_value = jo_inside.getString("formule");
            String url_value = jo_inside.getString("url");

            //Add your values in your `ArrayList` as below:
            m_li = new HashMap<String, String>();
            m_li.put("formule", formula_value);
            m_li.put("url", url_value);

            formList.add(m_li);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

【讨论】:

    猜你喜欢
    • 2012-09-09
    • 2023-04-05
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多