原文链接:对象和字符串之间的相互转换 – 编程屋
相关依赖:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.74</version> </dependency>
实体类: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字符串转为自己的实体类
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<Employee> employees = JSON.parseArray(data, Employee.class);
for (Employee employee :employees){
System.out.println(employee);
if (employee.getAddress() != null ) {
System.out.println("*******************"+employee.getAddress());
}
}
测试结果:
以上只是部分内容,为了维护方便,本文已迁移到新地址:对象和字符串之间的相互转换 – 编程屋