使用Java参数化构造函数反序列化json

Hi Guys in my previous blog JSON deserialize generic types using Gson and Jackson I talked about how you can deserialize json in Java Generics. Now in this blog post we are going to learn how to deserialize json into Java class which doesn’t have default constructor. For this blog I am using Jackson library.

Almost all frameworks requires default/no-argument constructor in your class. Because these frameworks use reflection to create objects by invoking default constructor. But if there is no default constructor present in class then its hard to instantiate using reflection. Let’s assume we have a class with no-args constructor (only a parameterized constructor present) and we want to deserialize it.

和一个json文件

在Jackson中,有两种方法可以反序列化此类。

  1. 自定义解串器混合注解

1. Custom Deserializer

在“自定义反序列化器”中,您将创建一个类并将其扩展为com.fasterxml.jackson.databind.JsonDeserializer并覆盖其抽象方法deserialize()。 此类可让您完全控制,您将获得jsoncom.fasterxml.jackson.core.JsonParser。 现在,您可以将json属性与类属性进行映射。 就我而言,我正在创建UserProfileDeserializer。

现在我们需要在上方注册反序列化器com.fasterxml.jackson.databind.ObjectMapper。 这样,在反序列化UserProfile类时,它会使用UserProfileDeserializer。

在上面的代码中,我们在com.fasterxml.jackson.databind.module.SimpleModule并且该模块已在com.fasterxml.jackson.databind.ObjectMapper。 同样,您也可以为其他类注册反序列化器。

2. Mixin Annotations

Jackson provides another way of doing this by using _ Mixin Annotations _. You can read about Jackson Mixin here. In our class UserProfile there is no default constructor, it has a parameterized constructor. Let’s checkout how to create mixin for our class.

而已 !!

我们创建了与中相同的构造函数用户资料课并标记为com.fasterxml.jackson.annotation.JsonCreator注解。 这将说明com.fasterxml.jackson.databind.ObjectMapper这是目标类别的方式(用户资料)构造函数外观和构造函数参数标有com.fasterxml.jackson.annotation.JsonProperty注解。

现在查看如何在中注册此mixin类com.fasterxml.jackson.databind.ObjectMapper

请享用 !!!! ☺☺

from: https://dev.to//jeetmp3/deserialize-json-with-java-parameterized-constructor-1gfl

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值