0
点赞
收藏
分享

微信扫一扫

对象和字符串之间的相互转换

unadlib 2022-03-12 阅读 134

相关依赖:

实体类:Employee

package com.liubujun.entity;


import lombok.Data;



/**
 * @Author: liubujun
 * @Date: 2022/2/24 10:01
 */

@Data
public class Employee {

    private Integer id;

    private String name;

    private Integer age;

    private String address;

    private String status;

    public Employee(Integer id, String name, Integer age, String address, String status) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.address = address;
        this.status = status;
    }
}

测试类:

 public static void main(String[] args) {
        String str = "{id:'100',name:'张三',age:'18',address:'五道口',status:'成功'}";
        /**
         * json字符串转为自己的实体类
         */
        Employee employee = JSON.parseObject(str, Employee.class);
        System.out.println(employee.toString());


        /**
         * 对象转换为JSON字符串
         */
        String string = JSON.toJSONString(employee);
        System.out.println(string);
    }

测试结果:

json字符串转为自己的实体类
对象转换为JSON字符串

json字符串转为object

 json格式为:

        String str = "{id:'100',name:'张三',age:'18',address:'五道口',status:'成功'}";

        JSONObject jsonObject = JSON.parseObject(str);
        System.out.println("jsonObject:"+jsonObject);
        String age = jsonObject.getString("age");
        System.out.println(age);
        

 json格式为:

        String str = "{success:'true',data:{id:'100',name:'张三',age:'18',address:'五道口',status:'成功'}}";

        JSONObject jsonObject = JSON.parseObject(str);
        System.out.println("jsonObject:"+jsonObject);
        String name = JSON.parseObject(jsonObject.getString("data")).getString("name");
        System.out.println(name);

测试结果:

 json格式为:

        String str = "{success:'true',data:[{id:'100'},{name:'张三'},{age:'18'},{address:'五道口'},{status:'成功'}]}";

        String data = JSON.parseObject(str).getString("data");
        List<Employee> employees = JSON.parseArray(data, Employee.class);
        for (Employee employee :employees){
            System.out.println(employee);
            if (employee.getAddress() != null ) {
                System.out.println("*******************"+employee.getAddress());
            }
        }

测试结果:

 

举报

相关推荐

0 条评论