[英]How to convert list map to json string and json to list map
I want to convert list map to json (First Activity) then json to list map (Third Activity) I am using built-in json library Don't Use Any Third party library I want to convert list map to json (First Activity) then json to list map (Third Activity) I am using built-in json library Don't Use Any Third party library
Code to convert ListMap to json将 ListMap 转换为 json 的代码
{
}
else
{
HashMap<Object, Object> map = new HashMap<>();
map.put("title",list_string_title);
map.put("id",list_string_id);
JSONObject jsonObject = new JSONObject(map);
FileUtils.writeFile(getPathData(scr_id),jsonObject.toString());
}
When the program find the json file I want it to add it into a listMap当程序找到 json 文件时,我希望它将其添加到 listMap
Need to pass a TypeReference
to readValue
with your output type需要使用您的 output 类型将TypeReference
传递给readValue
ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> data = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>(){});
You can iterate over the JSONObject and add it to the map, in your case your value is a list, it will be treated as JSONArray, you can try the following code您可以遍历 JSONObject 并将其添加到 map,在您的情况下,您的值是一个列表,它将被视为 JSONArray,您可以尝试以下代码
public Map<Object, Object> jsonToMap(JSONObject jsonObject) throws JSONException {
Iterator<String> itr = jsonObject.keys();
Map<Object, Object> mapFromJSON = new HashMap<Object,Object>();
while(itr.hasNext()) {
Object key = itr.next();
JSONArray jsonArray = (JSONArray) jsonObject.get((String) key);
ArrayList list = new ArrayList<Object>();
for(int i=0; i< jsonArray.length(); i++) {
list.add(jsonArray.get(i));
}
mapFromJSON.put(key, list);
}
return mapFromJSON;
}
if your list contains JSONObject, you can use recursion.如果您的列表包含 JSONObject,则可以使用递归。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.