Java Jackson

Maven

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.2</version>
</dependency>

Object to Json

1
2
ObjectMapper mapper = ObjectMapper()
String value = mapper.writeValueAsString(obj)

Json to Object

1
2
ObjectMapper mapper = new ObjectMapper();
Obj value = mapper.readValue(json_str, Obj.class);

util

1
2
3
4
5
6
7
8
9
10
11
object JsonUtil {
private val mapper = ObjectMapper()

fun toJson(obj: Any?): String {
return mapper.writeValueAsString(obj)
}

fun <T> fromJson(obj: String?, clazz: Class<T>): T? {
return mapper.readValue(obj, clazz)
}
}

Anotation

@JsonProperty

Error solution

Jackson with JSON: Unrecognized field, not marked as ignorable

1
2
3
4
@JsonIgnoreProperties(ignoreUnknown = true)
data class Obj {

}

data class

非Private可以直接生成Json字段,如果添加了Private,则无法生成Json字段,即使添加@JsonProperty也无效。

BigDecimal

必须设置浮点数使用BigDecimal类型

1
ObjectMapper().enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS)

JsonDeserializer

1
2
3
4
5
val mapper = JsonUtil.getMapper()
var module = SimpleModule()
module.addDeserializer(Order::class.java, OrdersDeserializer())
mapper.registerModule(module)
objectMapper.registerModule(module)