利用fastjson将对象、数组、List及Map转换成json字符串
package com.ant.jdk8.json; import com.alibaba.fastjson.annotation.JSONField;
import java.util.Date; public class User { private String name; private int age; @JSONField(format="yyyy-MM-dd HH:mm:ss") private Date hireDate; 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 Date getHireDate() { return hireDate; } public void setHireDate(Date hireDate) { this.hireDate = hireDate; } public User(String name, int age, Date hireDate) { this.name = name; this.age = age; this.hireDate = hireDate; } public User() { } }
package com.ant.jdk8.json; import com.alibaba.fastjson.JSON; import java.util.ArrayList; import java.util.Date; import java.util.List; public class JsonDemo { public static void main(String[] args) { convertObjToJson(); //convertArrayToJson(); //convertCollectionToJson(); } //将Java对象转换成json字符串 public static void convertObjToJson(){ User user = new User("tom",20,new Date()); String jsonString = JSON.toJSONString(user); System.out.println(jsonString); } //将数组转换成json字符串 public static void convertArrayToJson(){ User user1 = new User("tom",20,new Date()); User user2 = new User("jack",25,new Date()); User[] userArray = {user1,user2}; String jsonString = JSON.toJSONString(userArray); System.out.println(jsonString); } //将集合转换成json字符串 public static void convertCollectionToJson(){ List<User> userList = new ArrayList<>(); userList.add(new User("tom",20,new Date())); userList.add(new User("jack",25,new Date())); String jsonString = JSON.toJSONString(userList); System.out.println(jsonString); } }
package com.ant.jdk8.json; import java.util.HashMap; import java.util.Map; public class User { private String name; private Map<String,Integer> score = new HashMap<>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, Integer> getScore() { return score; } public void setScore(Map<String, Integer> score) { this.score = score; } public User(String name, Map<String, Integer> score) { this.name = name; this.score = score; } public User() { } }
package com.ant.jdk8.json; import com.alibaba.fastjson.JSON; import java.util.HashMap; import java.util.Map; public class JsonDemo { public static void main(String[] args) { convertMapToJson(); } public static void convertMapToJson(){ Map<String,Integer> score = new HashMap<>(); score.put("语文",80); score.put("数学",90); User user = new User("tom",score); String jsonString = JSON.toJSONString(user,true); System.out.println(jsonString); } }
posted on 2018-06-24 01:09 shammgod_code 阅读(1154) 评论(0) 编辑 收藏 举报