繁体   English   中英

如何将列表 map 转换为 json 字符串和 json 到列表 Z1D78DC8ED51214E518B5114FE24490AE

[英]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

将 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());
        }

当程序找到 json 文件时,我希望它将其添加到 listMap

需要使用您的 output 类型将TypeReference传递给readValue

ObjectMapper mapper = new ObjectMapper();
List<Map<String, Object>> data = mapper.readValue(json, new TypeReference<List<Map<String, Object>>>(){});

您可以遍历 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;
    }

如果您的列表包含 JSONObject,则可以使用递归。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM