来吧,展示!
package XXX;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.IOException;
public class Test {
/**
* 测试:不同类中,相同属性但类型不同之间的拷贝,以ObjectMapper为例
*
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Person person = new Person("John", "25");
ObjectMapper objectMapper = new ObjectMapper();
//设置禁用策略:禁用后,如果序列化的Java对象为空,则ObjectMapper将不会抛出异常,而是返回空JSON对象。
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
//将一个对象转换为JSON格式的字符串
String jsonString = objectMapper.writeValueAsString(person);
//将JSON格式的字符串转换为目标类型的对象
Employee targetObject = objectMapper.readValue(jsonString, Employee.class);
System.out.println(person);
System.out.println(targetObject);
}
@Data
@AllArgsConstructor
@NoArgsConstructor
private static class Person {
private String name;
private String age;
}
@Data
private static class Employee {
private String name;
private int age;
}
}
版权声明:本文为CS_370682原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。