Android List<Map<String,String>转json(例子)

package com.armslee.json.test.cases;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;

public class TestListMapJson {

    /**
     * @param Lavender
     */
    public static void main(String[] args) {
        Map<String,String> map1 = new HashMap<String,String>();
        Map<String,String> map2 = new HashMap<String,String>();
        Map<String,String> map3 = new HashMap<String,String>();
        List<Map<String,String>> list = new ArrayList<Map<String,String>>();
        map1.put("name","小明");
        map1.put("age","23");
        map1.put("sex","");
        list.add(map1);

        map2.put("name","小王");
        map2.put("age","24");
        map2.put("sex","");
        list.add(map2);

        map3.put("name","小张");
        map3.put("age","22");
        map3.put("sex","");
        list.add(map3);
        String jsonStr = JSONArray.fromObject(list).toString();
        
        JSONArray ja = JSONArray.fromObject(jsonStr);
        
        @SuppressWarnings({ "deprecation", "unchecked" })
        List<Map<String,String>> listBack = JSONArray.toList(ja, HashMap.class);
        
        System.out.println(listBack.size());
        int i = 0;
        for (Map<String, String> map : listBack) {
            i++;
            StringBuffer sb = new StringBuffer();
            sb.append(""+i+" 个MAP ---》");
            if(map.containsKey("name")){
                sb.append(" Name:"+map.get("name"));
            }
            if(map.containsKey("age")){
                sb.append(" Age:"+map.get("age"));        
            }
            if(map.containsKey("sex")){
                sb.append(" Sex:"+map.get("sex"));
            }
            
            System.out.println(sb.toString());
        }

    }

}

 

posted @ 2016-07-19 14:23  星辰之力  阅读(11147)  评论(0编辑  收藏  举报