JAVA:POJO&&JSON相互转换

 

使用com.alibaba.fastjson.JSON 中JSON.toJSONString(Object object)方法

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import gds.application.taskmanager.dto.TaskMasterDTO;
import gds.application.taskmanager.dto.TaskMasterDetailDTO;

import java.util.ArrayList;
import java.util.List;

public class MyUtil {
    public static void main(String[] args) {
        TaskMasterDTO taskMasterDTO = new TaskMasterDTO();
        taskMasterDTO.setTaskMasterID("1");
        taskMasterDTO.setFinishStatus("5");
        List taskMasterDetailList = new ArrayList();
        TaskMasterDetailDTO taskMasterDetailDTO = new TaskMasterDetailDTO();
        taskMasterDetailDTO.setTaskMasterID("11");
        taskMasterDetailDTO.setRuleName("我的规则");
        taskMasterDTO.setTaskMasterDetailDTO(taskMasterDetailDTO);
        TaskMasterDetailDTO taskMasterDetailDTO1 = new TaskMasterDetailDTO();
        taskMasterDetailDTO1.setTaskMasterID("12");
        taskMasterDetailDTO1.setRuleName("规则12");
        taskMasterDetailList.add(taskMasterDetailDTO1);
        TaskMasterDetailDTO taskMasterDetailDTO2 = new TaskMasterDetailDTO();
        taskMasterDetailDTO2.setTaskMasterID("22");
        taskMasterDetailDTO2.setRuleName("规则22");
        taskMasterDetailList.add(taskMasterDetailDTO2);
        taskMasterDTO.setTaskMasterDetailList(taskMasterDetailList);

        //POJO转json
        String json = JSON.toJSONString(taskMasterDTO);
        System.out.println(json);

        //json转POJO
        TaskMasterDTO tempaskMasterDTO = JSON.parseObject(json, TaskMasterDTO.class);
        System.out.println(tempaskMasterDTO);
    }
}

输出的json串

{"finishStatus":"5",
"taskMasterDetailDTO":{"ruleName":"我的规则","taskMasterID":"11"},
"taskMasterDetailList":[
      {"ruleName":"规则12","taskMasterID":"12"},
	  {"ruleName":"规则22","taskMasterID":"22"}],
"taskMasterID":"1"}

 

你可能感兴趣的:(DTO转json,JAVA)