<dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.2</version> </dependency>
对数据的操作:
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.reflect.TypeToken; import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.*; import static jdk.nashorn.internal.objects.Global.print; /** * @Author : JCccc * @CreateTime : 2018-11-27 * @Description : * @Point: Keep a good mood **/ public class testMain { public static void main(String[] args) { //手动创的一个实体类, 里面字段全是String类型 User userTest=new User(); userTest.setName("joke"); userTest.setAge("16岁"); userTest.setHeight("60Kg"); userTest.setSex("男"); Gson gson=new Gson(); String jsonStr=gson.toJson(userTest,User.class); System.out.println("对象转JSON---"+jsonStr); User userTestNew=gson.fromJson(jsonStr,User.class); System.out.println("JSON转对象---"+userTestNew.toString()); Map map=new LinkedHashMap(); map.put("name","merry"); map.put("age","17岁"); map.put("height","62Kg"); map.put("sex","女"); String mapJsonStr=gson.toJson(map); System.out.println("map转JSON---"+mapJsonStr); List<User> userList = new ArrayList<>(); userList.add(userTest); // System.out.println(userList.toString()); String listJsonStr=gson.toJson(userList); System.out.println("list转JSON---"+listJsonStr); List<User> retList = gson.fromJson(listJsonStr,new TypeToken<List<User>>(){}.getType()); System.out.println("listJSON转list---"+retList); //报错 // List<User> retList1 = gson.fromJson(mapJsonStr,new TypeToken<List<User>>(){}.getType()); // System.out.println("mapJSON转list---"+retList1); //报错 /*List<User> retList2 = gson.fromJson(jsonStr,new TypeToken<List<User>>(){}.getType()); System.out.println("对象JSON转list---"+retList2);*/ } }
运行结果:
对象转JSON---{"name":"joke","age":"16岁","height":"60Kg","sex":"男"}
map转JSON---{"name":"merry","age":"17岁","height":"62Kg","sex":"女"}
JSON转对象---User{name='merry', age='17岁', height='62Kg', sex='女'}
list转JSON---[{"name":"joke","age":"16岁","height":"60Kg","sex":"男"}]
listJSON转list---[User{name='joke', age='16岁', height='60Kg', sex='男'}]
好了,小记到此。