栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

相关依赖:


  com.alibaba
  fastjson
  1.2.74

实体类:Employee

package com.liubujun.entity;


import lombok.Data;





@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:'成功'}";
        
        Employee employee = JSON.parseObject(str, Employee.class);
        System.out.println(employee.toString());


        
        String string = JSON.toJSonString(employee);
        System.out.println(string);
    }

测试结果:

json字符串转为自己的实体类

Employee employee = JSON.parseObject(str, Employee.class);
对象转换为JSON字符串
String string = JSON.toJSonString(employee);

json字符串转为object

JSonObject jsonObject = JSON.parseObject(str);

 json格式为:

{    

"id" : "100",    

"name" : "张三",    

"age" : "18",  

"address"  :"五道口",  

 "status" : "成功"

}

        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格式为:

{    

“success” : “true”,

"data" : {

"id" : "100",    

"name" : "张三",    

"age" : "18",  

"address"  :"五道口",  

 "status" : "成功"

}

}

        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格式为:

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

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

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

测试结果:

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/759773.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号