How to convert a Vector to JSONArray?

你说的曾经没有我的故事 提交于 2019-12-25 04:55:12

问题


I need to convert a Vector<Vector<Float>> to a JSONArray. Apart from iterating through the vector and creating the JSONArray, is there any simpler way to do this?

Someone told me to try gson.


回答1:


SharedPreferences is just a key-value store. What's stopping you from bypassing JSONObject completely, and just using something like this (Gson only)?

private static final Type DATA_TYPE = 
    new TypeToken<Vector<Vector<Float>>>() {}.getType();

Storage:

Vector<Vector<Float>> data = new Vector<Vector<Float>>();
data.add(new Vector<Float>());
data.get(0).add(3.0f);

String dataAsJson = new Gson().toJson(data, DATA_TYPE);
sharedPreferences.edit().putString("data", dataAsJson).commit();

Retrieval:

String dataAsJson = sharedPreferences.getString("data", "[]");
Vector<Vector<Float>> data = new Gson().fromJson(dataAsJson, DATA_TYPE);

Disclaimer: I've never developed for Android.



来源:https://stackoverflow.com/questions/11954578/how-to-convert-a-vector-to-jsonarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!