[Spring]~Json(jackson常用注解及方法)

序列化简介

个人理解,Json就是一种大家通用的数据传输格式。
提起Json,就不得不说下序列化和反序列化。

序列化

将代码中的实体数据转换成Json这种格式,便于数据传递与各类系统。

反序列化

将Json数据转换成代码中的实体数据。

代码

JsonTestModel jsonTestModel = new JsonTestModel();
jsonTestModel.setName("@JsonIgnoreProperties测试");
jsonTestModel.setTime(new Date());
testModel = jsonTestModel;
ObjectMapper mapper = new ObjectMapper();
//序列化
String json = mapper.writeValueAsString(testModel);
json = "{\"name\":\"@JsonIgnoreProperties测试\",\"time\":1575431118191}";
//反序列化
JsonTestModel readValue = mapper.readValue(json, JsonTestModel.class);

常用注解

@JsonIgnore(单字段序列化控制)

@JsonIgnoreProperties(类级序列化控制)

@JsonIgnoreType(该类作为别的类的属性时忽略序列化)

@JsonProperty(字段映射名称)

@JsonPropertyOrder(序列化时字段排序)

@JsonInclude(不序列化空字段)

@JsonBackReference和@JsonManagedReference(解决对象中存在双向引用导致的无限递归)

@JsonFormat(反序列化时,时间格式问题)

常用方法

json文件的读取

json文件

{
  "name": "測試",
  "time": "2019-12-04 00:00:00"
}

main方法

public class JsonUtils {

    public static void main(String[] args) {
        String json = "null";
        try {
            json = readJsonData("F:\\IdeaProject\\test\\demo\\src\\main\\resources\\json/readJson.json");
        } catch (IOException e) {
            e.printStackTrace();
        }
        JsonTestModel jsonTestModel= JSONObject.parseObject(json,JsonTestModel.class);
        System.out.println(jsonTestModel.getName());
        System.out.println(jsonTestModel.getTime());

    }

    public static String readJsonData(String path) throws IOException {

        StringBuffer strbuffer = new StringBuffer();
        File myFile = ResourceUtils.getFile(path);

        FileInputStream fis = new FileInputStream(myFile);
        InputStreamReader inputStreamReader = new InputStreamReader(fis, "UTF-8");
        BufferedReader in = new BufferedReader(inputStreamReader);

        String str;
        while ((str = in.readLine()) != null) {
            strbuffer.append(str);  //new String(str,"UTF-8")
        }
        fis.close();
        inputStreamReader.close();
        in.close();

        return strbuffer.toString();
    }

}

spring boot test

public class JsonUtilsTest {

    @Test
    public void test(){

        String json = "null";
        try {
            json = readJsonData("classpath:json/readJson.json");
        } catch (IOException e) {
            e.printStackTrace();
        }
        JsonTestModel jsonTestModel= JSONObject.parseObject(json,JsonTestModel.class);
        System.out.println(jsonTestModel.getName());
        System.out.println(jsonTestModel.getTime());

    }

}

结果

測試
Wed Dec 04 00:00:00 CST 2019
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值