mport java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
?
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class JacksonObjectMapperExample {
?
? ? public static void main(String[] args) throws IOException {
? ? ? ?
? ? ? ? //read json file data to String
? ? ? ? byte[] jsonData = Files.readAllBytes(Paths.get("C:\\employee.txt"));
? ? ? ?
? ? ? ? //create ObjectMapper instance
? ? ? ? ObjectMapper objectMapper = new ObjectMapper();
? ? ? ?
? ? ? ? //convert json string to object
? ? ? ? Employee emp = objectMapper.readValue(jsonData, Employee.class);
? ? ? ?
? ? ? ? System.out.println("Employee Object\n"+emp);
? ? ? ?
? ? ? ? //convert Object to json string
? ? ? ? Employee emp1 = createEmployee();
? ? ? ? //configure Object mapper for pretty print
? ? ? ? objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
? ? ? ?
? ? ? ? //writing to console, can write to any output stream such as file
? ? ? ? StringWriter stringEmp = new StringWriter();
? ? ? ? objectMapper.writeva lue(stringEmp, emp1);
? ? ? ? System.out.println("Employee JSON is\n"+stringEmp);
? ? }
? ?
? ? public static Employee createEmployee() {
?
? ? ? ? Employee emp = new Employee();
? ? ? ? emp.setId(100);
? ? ? ? emp.setName("David");
? ? ? ? emp.setPermanent(false);
? ? ? ? emp.setPhoneNumbers(new long[] { 123456, 987654 });
? ? ? ? emp.setRole("Manager");
?
? ? ? ? Address add = new Address();
? ? ? ? add.setCity("Bangalore");
? ? ? ? add.setStreet("BTM 1st Stage");
? ? ? ? add.setZipcode(560100);
? ? ? ? emp.setAddress(add);
?
? ? ? ? List cities = new ArrayList();
? ? ? ? cities.add("Los Angeles");
? ? ? ? cities.add("New York");
? ? ? ? emp.setCities(cities);
?
? ? ? ? Map props = new HashMap();
? ? ? ? props.put("salary", "1000 Rs");
? ? ? ? props.put("age", "28 years");
? ? ? ? emp.setProperties(props);
?
? ? ? ? return emp;
? ? }
?
}
结果如下:
Employee Object
***** Employee Details *****
ID=123
Name=Pankaj
Permanent=true
Role=Manager
Phone Numbers=[123456, 987654]
Address=Albany Dr, San Jose, 95129
Cities=[Los Angeles, New York]
Properties={age=29 years, salary=1000 USD}
*****************************
Employee JSON is
{
? "id" : 100,
? "name" : "David",
? "permanent" : false,
? "address" : {
? ? "street" : "BTM 1st Stage",
? ? "city" : "Bangalore",
? ? "zipcode" : 560100
? },
? "phoneNumbers" : [ 123456, 987654 ],
? "role" : "Manager",
? "cities" : [ "Los Angeles", "New York" ],
? "properties" : {
? ? "salary" : "1000 Rs",
? ? "age" : "28 years"
? }
}
总结
本文以一个完整的示例总结了Java对象序列化为Json对象和反序列化的过程,希望可以抛砖引玉对大家有所帮助。