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
{
}
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
Need to pass a TypeReference
to readValue
with your output type
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
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.