您的位置:首页 > 编程语言 > Java开发

java集合的运用,把数组和对象的json格式,转换成对象和数组的格式

2018-01-10 09:43 666 查看
package com.yanshu.utils;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Set;

import org.jboss.jandex.Main;

import com.alibaba.fastjson.JSON;

public class MapUtil {

public static String ListTojson(List<HashMap> map2){
if(map2.size()==0){
return "{}";
}
Map<String,List> map=new HashMap<String,List>();
Set<String> set=map2.get(0).keySet();
for (String setchild : set) {
map.put(setchild, new ArrayList<>());
}

for (int i = 0; i < map2.size(); i++) {
for (String str : set) {
map.get(str).add(map2.get(i).get(str)==null?0:map2.get(i).get(str));
}
}
return   JSON.toJSONString(map);
}

public static String  ListTurnMap(List<HashMap> maps)
{
//如何长度等于0,返回空
if(maps.size()==0)
{
return "{}";
}
Map<String,List> map=new HashMap<>();
Set<String> set=maps.get(0).keySet();//获取List<HashMap> maps的第一个键
System.out.println("set--->>>"+set);
for (String setchild : set) {
map.put(setchild,new ArrayList<>());//[{tom=23, mary=12}, {tom=33, mary=22}]转换成{tom=[], mary=[]}
}
System.out.println("map-->>"+map);
//填值
for(int i=0;i<maps.size();i++)
{
for (String str : set) {
//map.get(str).a
4000
dd(map2.get(i).get(str)==null?0:map2.get(i).get(str));
map.get(str).add(maps.get(i).get(str)==null?0:maps.get(i).get(str));

}
}

return   JSON.toJSONString(map);//{"tom":[23,33],"mary":[12,22]}

}

public static void main(String[] args) {
Map map1=new HashMap<>();
Map map2=new HashMap<>();
map1.put("tom",23);
map1.put("mary",12);
map2.put("tom",33);
map2.put("mary",22);
List list=new ArrayList();
list.add(map1);
list.add(map2);
System.out.println(list);
String listTojson = ListTurnMap(list);

System.out.println(listTojson);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: