借助Lambda表达式将json字符串转成Map<String,List<Object>>类型  今天上班时遇到了这个问题,顺便记⼀下,废话不多说,直接上代码
1.⾃⼰造的⼀个实体类如下:
sc.json_to_map;
public class Dog {
private String name;
private int age;
private String color;
public Dog(String name,int age, String color){
super();
this.name = name;
this.age = age;
}
public String getName(){return name;}
public void setName(String name){this.name = name;}
public int getAge(){return age;}
public void setAge(int age){this.age = age;}
public String getColor(){return color;}
public void setColor(String color){lor = color;}
@Override
public String toString(){
return"Dog [name="+ name +", age="+ age +", color="+ color +"]";
}
}
2.解决⽅式如下:
sc.json_to_map;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.stream.Collectors;
import com.alibaba.fastjson.JSONObject;
public class Demo {
public static void main(String[] args){
/** ⼩明狗的集合 */
Dog[] XM_DOG ={new Dog("⼤黄",2,"黄⾊"),
new Dog("⼩⿊",3,"⿊⾊")};
List<Dog> XM_DOG_List = Arrays.asList(XM_DOG);
/** ⼩亮狗的集合 */
Dog[] XL_DOG ={new Dog("⼆狗",6,"⿊⽩⾊"),
new Dog("卷⽑",5,"⽩⾊")};
List<Dog> XL_DOG_List = Arrays.asList(XL_DOG);
Map<String, List<Dog>> map =new HashMap<>();
object tomap.put("xiaoming", XM_DOG_List);
map.put("xiaoliang", XL_DOG_List);
// 利⽤FastJson先将map转为json字符串
String jsonString = JSONString(map);
System.out.println(jsonString);
System.out.println("=================================================================");
/** 获取到JSONObject */
JSONObject parseObject = JSONObject.parseObject(jsonString);
/** Set()获取到Set集合 */
Set<Entry<String, Object>> entrySet = Set();
/
** set集合⾥都有什么 */
for(Entry<String, Object> entry : entrySet){
System.out.Key());
System.out.Value());
}
System.out.println("=================================================================");
/**
* 熟悉了JSONObject以及Set()之后
* 就可以⽐较容易地明⽩怎么通过lambda表达式将整个json字符串转换成Map<String,List<Dog>>了
*
* 表达式如下:
*/
Map<String, List<Dog>> result = JSONObject.parseObject(jsonString).entrySet()
.stream().Map(Map.Entry::getKey,
entry -> JSONObject.parseArray(String.Value()), Dog.class)));
List<Dog> list = ("xiaoming");
List<Dog> list2 = ("xiaoliang");
System.out.println(list);
System.out.println(list2);
}
}
贴⼀下运⾏结果

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。