【MapSheep】
[好记性不如烂笔头]


解析入参

Map<String,Object> param = JSON.parseObject(JSON.toJSONString(requestDTO.getBody()), Map.class);
icd10Name = (String) param.get(ICD10NAME);

代码展示

@Test
public void SendCash(){
	List<Student> objects = new ArrayList<>();
	Collections.addAll(objects,
			new Student("王通通","男",12,"2班"), new Student("闫晓雨","女",18,"1班"), new Student("高佳琪","男",20,"4班"));
	//使用排序
	//  Collections.sort(objects,Comparator.comparing(Student::getClazz));
	//  objects.stream().forEach(v -> System.out.println(v.getName()+":"+v.getClazz()));

	//将Java Bean转换为JSON字符串对象
	String s = JSON.toJSONString(new Student("王步嵩", "男", 26,"8班"));
	System.out.println("转换对象之后"+s);

	//将JSON转换为Java Bean
	Student student = JSON.parseObject(s,Student.class);
    //或者说这样
    Student student = JSON.parseObject(JSON_OBJ_STR, new TypeReference<Student>() {}); 
	System.out.println("转换对象之前"+student);

	//将多个JSON对象放入到Java集合中
	List<Student> studentList = JSON.parseArray(JSON.toJSONString(objects), Student.class);
	Iterator<Student> iterator = studentList.iterator();
	while(iterator.hasNext()){
		Student next = iterator.next();
		System.out.println(next.getName()+":"+next.getAge());
	}

	//将Java Ben转换为jsonObject便于使用getString() 取出一个值方法
	JSONObject jsonObject = (JSONObject)JSON.toJSON(new Student("白志超", "男", 36,"12班"));
	System.out.println(jsonObject.getString("name"));

}

class JSONS {
    static void JS() {
        List<Student> list = new ArrayList<>();
        Student student = new Student("张三", "男", "1");
        Collections.addAll(list, student, new Student("李四", "女", "2"), new Student("王五", "女", "2"));

        System.out.println("*******javaBean  to jsonString*******");
        String stu = JSON.toJSONString(student);
        System.out.println(stu);
        System.out.println("\t" + JSON.toJSONString(list));

        System.out.println("******jsonString to javaBean*******");
        Student parseClass = JSON.parseObject(stu, Student.class);
        System.out.println("转换前\t" + parseClass);
        JSONObject jsonObject = JSON.parseObject(stu);
        System.out.println("转换后\t" + jsonObject);

        System.out.println("******javaBean to jsonObject******");
        JSONObject o = (JSONObject) JSON.toJSON(student);
        System.out.println(o);
        System.out.println(o.getString("name"));

        System.out.println("******jsonObject to javaBean******");
        Student JavaObJ = JSON.toJavaObject(o, Student.class);
        System.out.println(JavaObJ);

        System.out.println("*****jsonObject to jsonString*****");
        System.out.println(JSON.toJSONString(student));


        System.out.println("*******jsonString to jsonObject*****");
        JSONObject jso1 = JSON.parseObject(stu);
        System.out.println(jso1.getString("name"));
        System.out.println();
    }

    static void jQuery() {
        System.out.println("*******javaBean to jsonArray******");
        List<Student> list = new ArrayList<>();
        for (int i = 0; i < 6; i++) {
            Collections.addAll(list, new Student("姓名" + i, "性别" + i, "年级" + i));
        }
        JSONArray o = (JSONArray) com.alibaba.fastjson.JSON.toJSON(list);
        for (int i = 0; i < o.size(); i++) {
            System.out.println(o.get(i));
        }
        System.out.println();

        System.out.println("*****jsonArry to javalist******");
        List<Student> myList = new ArrayList<>();
        for (int i = 0; i < o.size(); i++) {
            myList.add(com.alibaba.fastjson.JSON.toJavaObject(o.getJSONObject(i), Student.class));
        }
        for (Iterator<Student> iterator = myList.iterator(); iterator.hasNext(); ) {
            Student next = iterator.next();
            System.out.println(next);
        }

    }
}

把数组中的值存入到下面List集合中

// requestDTO.getBody()----把数组中的值存入到下面List集合中
// List<ApprovalReturnInfoDTO> array=JSON.parseArray(JSON.toJSONString(requestDTO.getBody()),ApprovalReturnInfoDTO.class);

class ApprovalReturnInfoDTO implements Serializable {

    /**
     * 序列化
     */
    private static final long serialVersionUID = 700674671863229028L;

    /**
     * id
     */
    private String uuid;

    /**
     * 编码
     */
    private String code;

    /**
     * 名称
     */
    private String name;

    /**
     * 异常描述
     */
    private String errorReason;
}

参数拼接

//参数处理
JSONObject jsonObjectCe = new JSONObject();
JSONObject head = new JSONObject();
head.put("requestType", "090028");
head.put("unitCode", "01");
head.put("userCode", "01040181");
jsonObjectCe.put("head", head);
JSONObject body = new JSONObject();
body.put("caseno", requestJson.getString("caseno"));    //获取参数为JSONObject中里面为caseno的参数
jsonObjectCe.put("body", body);

格式化展示

  1. 占位符
    • jsonObject.getString(""age"")

    • 注意
      • 需要两个Jar包配合使用
        • junit-4.12.jar
        • hamcrest-core-1.3.jar
    • APP报文 0:在线 1:不在线
{
	"resCode":"0000",
	"resMsg":"成功",
	"resultContent":{
		"userStatus":"0",
		"userCode":"24584568",
		"platform":"PC"
	}
}

超强工具类

//HTTP请求返回数据,根据工号对比在线人数,返回在线状态
String url = ClaimUrlConfigConstants.SEND_CAR_URL;
String body = HttpRequest.post(url + "/sunRTC/request").timeout(2000)
		.body(JSONObject.toJSONString(headDTO))
		.execute()
		.body();
JSONObject obj = (JSONObject)JSON.parse(body); //将body转换为JSONObject格式
if(obj != null){
	String resCode = obj.getString("resCode"); //使用getString取出JSONObject中的值
	if("0000".equals(resCode)){
		List<UserInfoVo> userList = JSON.parseArray(obj.getString("resultContent"), UserInfoVo.class); //取出数据,放入至集合中
		for (UserInfoVo userInfo:userInfoVoList) {
			userInfo.setPostName(userInfo.getPostName());
			userList.forEach(userIfo->{
				//获取工具在线信息
				userInfo.setPlatform(userIfo.getPlatform());

				if(userIfo.getUserCode().equals(userInfo.getUserCode())){
					userInfo.setState("0");
				}else {
					userInfo.setState("1");
				}
			});
		}
	}
}

JSON 集合转换

//把数据转换到List集合中01
List<PolicyInfo> ts = (List<PolicyInfo>) JSONArray.parseArray(JSON.toJSONString(data.getPolicyInfos()), PolicyInfo.class);

// 把数据转换到List集合中02
List<PolicyInfo> policyInfoList = JSONArray.parseArray(JSON.toJSONString(data.getPolicyInfos()), PolicyInfo.class);

// 第三种方式
ArrayList<Student> students = JSON.parseObject(JSON_ARRAY_STR, new TypeReference<ArrayList<Student>>() {});

复杂json格式字符串与JSONObject之间的转换


转换为 数组 和 JSONObject

// 1. JSON格式字符串与JSON对象之间的转换。1.json字符串-简单对象型 与 JSONObject之间的转换
JSONObject jsonObject1 = JSON.parseObject(JSON_OBJ_STR);

// 2. json字符串-数组类型与JSONArray之间的转换
JSONArray jsonArray = JSON.parseArray(JSON_ARRAY_STR);

//遍历方式1
int size = jsonArray.size();
for (int i = 0; i < size; i++) {
	JSONObject jsonObject = jsonArray.getJSONObject(i);
}

//遍历方式2
for (Object obj : jsonArray) {
	JSONObject jsonObject = (JSONObject) obj;
}


outer

  1. 占位符
    • 接下来阐述正文:(其实是copy其他人的博客,主要放在自己博客下面好找...........................)
    • 华丽的分割线=====================
      • JSON:fastJson的解析器,用于JSON格式字符串与JSON对象及javaBean之间的转换。
      • JSONObject:fastJson提供的json对象。
      • JSONArray:fastJson提供json数组对象。首先定义了三个json格式的字符串作为我们的数据源

前端传值【FastJson学习:JSON格式字符串、JSON对象及JavaBean之间的相互转换】

  1. 占位符
    • 当前台需要传送一系列相似数据到后端时,可以考虑将其组装成json数组对象,然后转化为json形式的字符串传输到后台
    nodes = $('#PmPbsSelect_tree').tree('getChecked');
    var data=[];
    for(var i=0;i<nodes.length;i++){
        if(!isParentCheck(nodes[i],nodes)){
            data.push({"id":nodes[i].id,
                "pid":node.id});
        }else{
            data.push({"id":nodes[i].id,
                "pid":null});
        }
    }    
    dataStr=JSON.stringify(data);    
    $.ajax({
         url:ctx+"/PmWbs/savePmWbsByModel",
         type:"POST",
         data:{"dataStr":dataStr,
             "projectId":pmProjectSelect.combobox('getValue')},
         success:function(data){
             basetree.tree('reload');
         },
         error:function(){
             alert("请求失败");
         },
         dataType:"json"
     });

JSON 转换集合 and 单个 Bean操作

* JSON转换JavaBean


* JSON转换集合JavaBean

import com.alibaba.fastjson.JSON;

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

public class Test02 {


    //json字符串-简单对象型
    private static final String JSON_OBJ_STR = "{\"studentName\":\"lily\",\"studentAge\":12}";
    //json字符串-数组类型
    private static final String JSON_ARRAY_STR = "[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]";
    //复杂格式json字符串
    private static final String STGR01 = "{\"teacherName\":\"张三\",\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}";
    private static final String STGR02 = "{\"teacherName\":\"李四\",\"teacherAge\":27,\"course\":{\"courseName\":\"english\",\"code\":1270},\"students\":[{\"studentName\":\"lily\",\"studentAge\":12},{\"studentName\":\"lucy\",\"studentAge\":15}]}";


    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add(STGR01);
        list.add(STGR02);

        //1. JSON转换为对象Bean
        Teacher parseObject = JSON.parseObject(String.valueOf(STGR01), Teacher.class);
        System.out.println(parseObject.toString());
        /*
            Teacher{teacherName='张三', teacherAge=27, course=Course@1c4af82c, students=[Student@379619aa, Student@cac736f]}
        */

        //2. JSON转换为集合Bean
        List<Teacher> teacherList = JSON.parseArray(list.toString(), Teacher.class);
        teacherList.forEach(teacher -> {
            System.out.println("师傅:" + teacher.getTeacherName() + "徒弟:" + JSON.toJSON(teacher.getStudents()));
        });
        /*
            师傅:张三徒弟:[{"studentAge":12,"studentName":"lily"},{"studentAge":15,"studentName":"lucy"}]
            师傅:李四徒弟:[{"studentAge":12,"studentName":"lily"},{"studentAge":15,"studentName":"lucy"}]
        */
    }
}


class Course {

    private String courseName;
    private Integer code;

    public String getCourseName() {
        return courseName;
    }

    public void setCourseName(String courseName) {
        this.courseName = courseName;
    }

    public Integer getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }
}

class Student {

    private String studentName;
    private Integer studentAge;

    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public Integer getStudentAge() {
        return studentAge;
    }

    public void setStudentAge(Integer studentAge) {
        this.studentAge = studentAge;
    }
}

class Teacher {

    private String teacherName;
    private Integer teacherAge;
    private Course course;
    private List<Student> students;

    public String getTeacherName() {
        return teacherName;
    }

    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }

    public Integer getTeacherAge() {
        return teacherAge;
    }

    public void setTeacherAge(Integer teacherAge) {
        this.teacherAge = teacherAge;
    }

    public Course getCourse() {
        return course;
    }

    public void setCourse(Course course) {
        this.course = course;
    }

    public List<Student> getStudents() {
        return students;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "teacherName='" + teacherName + '\'' +
                ", teacherAge=" + teacherAge +
                ", course=" + course +
                ", students=" + students +
                '}';
    }
}
posted on 2021-02-05 11:08  (Play)  阅读(152)  评论(0编辑  收藏  举报