Java:DTO JSON VO List之间转换

使用场景

Java常常需要处理dto,vo,json之间的转换。

处理思路

1. DTO转VO

BeanUtils.copyProperties(applyDto, apply);

2. JSON转VO

JSONObject jsonObject = JSONObject.fromObject(jsonStr);
Apply apply = (Apply) JSONObject.toBean(jsonObject, Apply.class);

3. JSON转DTO

Map<String, Class> classMap = new HashMap<String, Class>();
classMap.put("applySuccesss", ApplySuccess.class);
classMap.put("applyErrors", ApplyError.class);
JSONObject jsonObject = JSONObject.fromObject(jsonStr);
ApplyDto applyDto = (ApplyDto) JSONObject.toBean(jsonObject, ApplyDto.class, classMap);
public class ApplyDto extends Apply {
	private List<ApplySuccess> applySuccesss;
	private List<ApplyError> applyErrors;
	private Integer applycount;
	...
}

4. JSON与List转换

  • fastJson
//list -> json
List<Student> list = new ArrayList<Student>();
String str=JSON.toJSON(list).toString();
 
//json -> list
List<Student> list = new ArrayList<Student>();  
list = JSONObject.parseArray(jasonArray, Student.class);  
  • Gson
//list -> json
Gson gson = new Gson();  
List<Student> students = new ArrayList<Student>();  
String str = gson.toJson(students);  
 
//json -> list
Gson gson = new Gson();  
List<Student> students = gson.fromJson(str, new TypeToken<List<Student>>(){}.getType());  

你可能感兴趣的:(Java技术,java)