jackson 反序列化string_Jackson序列化和反序列化Json数据完整示例

import java.io.File;

import java.io.IOException;

import 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.writeValue(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;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值