码迷,mamicode.com
首页 > Web开发 > 详细

fastJson转换对象与字符串

时间:2018-05-24 11:54:06      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:fastJson转换对象与字符串

static class TempClass{
private String name;
private int 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 static void main(String[] args) {
Map<String, List<Test.TempClass>> map = new HashMap<String, List<Test.TempClass>>();
Random random = new Random();
for(int i = 1 ; i < 3 ;i++){
List<Test.TempClass> list = new ArrayList<Test.TempClass>();
for(int j = 1 ; j < 3 ;j++) {
TempClass tempClass = new TempClass();
int r = random.nextInt(500);
tempClass.name = r +"name";
tempClass.age = r ;
list.add(tempClass);
}
map.put(UUID.randomUUID().toString(),list);
}
//===============对象转字符串=====================================
String jsonString = JSON.toJSONString(map);
System.out.println(jsonString);
//===============字符串转对象===========================
Map<String, List<?>> mapObj = (HashMap<String, List<?>>)JSON.parseObject(jsonString, HashMap.class);
Map<String, List<TempClass>> mapList = (HashMap<String, List<TempClass>>)JSON.parseObject(jsonString, HashMap.class);
for(Map.Entry<String, List<?>> entry : mapObj.entrySet()){
// 此时entry.getValue()并不具备类型信息,需要再做深层的解析
List<TempClass> list = (List<TempClass>)JSONArray.parseArray(entry.getValue().toString(), TempClass.class);
mapList.put(entry.getKey(),list);
}
}

fastJson转换对象与字符串

标签:fastJson转换对象与字符串

原文地址:http://blog.51cto.com/12165865/2119748

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!