上一篇提到,JSON是一种轻量级的、高效的数据传输格式,那么Json和Java对象之间,应该如何转化呢。
通常使用较多的类库是GSON和FastJson。
一、GSON
GSON是Google提供用来转换Java对象和JSON数据的类库,可以将Json字符串转化为Java对象,或者将Java对象转化为JSON字符串。
1、直接new Gson对象
//使用new方法
Gson gson = new Gson();
String gsonStr = "{\"id\":1,\"flowRoleId\":1,\"flowRoleName\":\"巡检员\",\"userId\":82,\"userName\":\"张三\"}";
String gsonList = "[{\"id\":1,\"flowRoleId\":1,\"flowRoleName\":\"巡检员\",\"userId\":82,\"userName\":\"李海天\"},{\"id\":2,\"flowRoleId\":2,\"flowRoleName\":\"值班室\",\"userId\":83,\"userName\":\"李震\"},{\"id\":3,\"flowRoleId\":2,\"flowRoleName\":\"值班室\",\"userId\":77,\"userName\":\"金佳骏\"}]";List<FlowRoleUser> listFlow = new ArrayList<>();
FlowRoleUser flowRoleUser1 = new FlowRoleUser();
flowRoleUser1.setFlowRoleName("主管");
FlowRoleUser flowRoleUser2 = new FlowRoleUser();
flowRoleUser2.setFlowRoleName("值班室");
flowRoleUser2.setUserName("李四");
listFlow.add(flowRoleUser1);
listFlow.add(flowRoleUser2);
- fromJson
将Json字符串转化为JavaBean
FlowRoleUser flowRoleUser = gson.fromJson(gsonStr, FlowRoleUser.class);
- toJson
将JavaBean转化为Json字符串
String jsonStr2 = gson.toJson(flowRoleUser2, FlowRoleUser.class);
- 序列化List
String jsonList = gson.toJson(listFlow);
- 反序列化为List
List<FlowRoleUser> list = gson.fromJson(gsonList, new TypeToken<List<FlowRoleUser>>(){}.getType());