我创建了一个ArrayList,我需要将其转换为JSONarray:
这就是我ArrayList<model>
中的对象的样子:
modelList.add(new model("String", 9.99 /*Double*/, null /*Date*/, R.drawable.drawable, R.color.color, 1 /*int*/, 0 /*int*/));
...
这是我到目前为止所尝试的:
public void saveArrayListtoJSON(ArrayList<Model> modelList) {
JSONArray myJSONArray = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("key", modelList);
myJSONArray.put(obj);
}
}
答案 0 :(得分:2)
您可以尝试这样:
public void saveArrayListtoJSON(ArrayList<Model> modelList) {
JSONArray myJSONArray = new JSONArray();
JSONObject obj = new JSONObject();
for(Model model : modelList){
try {
obj.put("key", model);
} catch (JSONException e) {
e.printStackTrace();
}
myJSONArray.put(obj);
}
}
还原任何错误。
答案 1 :(得分:2)
在build.gradle
compile 'com.google.code.gson:gson:2.7'
然后
String str = new Gson().toJson(modelList);
JSONObject jsonObject = new JSONObject(str);
答案 2 :(得分:1)
你也可以使用gson,只需将arraylist作为参数。但是如果不使用瞬态去除模型中不可序列化的对象,那么你的模型的所有元素都需要是可序列化的
Gson - putting and getting ArrayList of composite objects
看看这里: Google Gson - deserialize list<class> object? (generic type)
答案 3 :(得分:1)
您可以使用Gson将ArrayList转换为JSON数组
Gson gson = new Gson();
String json = gson.toJson(yourArraylist);