JackSon对Java对象的序列化与反序列化
package com.lius.DistributedProject.RPC.rpc_json; import java.io.IOException; import java.io.StringWriter; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.ObjectMapper; import com.lius.DistributedProject.RPC.rpc_json.domain.person; //json 对象的序列化和反序列化 JackSon public class jsonSerialize { public static void main(String[] args) throws IOException { person person = new person(); person.setUsername("tom"); person.setAge(20); person.setAddress("XXX"); //序列化为json字符串 ObjectMapper mapper = new ObjectMapper(); StringWriter sw = new StringWriter(); JsonGenerator generator = new JsonFactory().createGenerator(sw); mapper.writeValue(generator, person); String jsonStr = sw.toString(); System.out.println(jsonStr); //Json字符串转换为对象 person obj = mapper.readValue(jsonStr, person.getClass()); System.out.println(obj); } }
JackSon对Java对象的序列化与反序列化
最新推荐文章于 2023-03-03 13:56:43 发布