JSON

Spring Boot 提供与三个 JSON 映射库的集成

  • Gson

  • Jackson

  • JSON-B

Jackson 是首选的默认库。

Jackson

提供了 Jackson 的自动配置,并且 Jackson 是 spring-boot-starter-json 的一部分。当 Jackson 在类路径上时,会自动配置 ObjectMapper bean。提供了几个配置属性用于 自定义 ObjectMapper 的配置

自定义序列化器和反序列化器

如果您使用 Jackson 序列化和反序列化 JSON 数据,您可能希望编写自己的 JsonSerializerJsonDeserializer 类。自定义序列化器通常 通过模块注册到 Jackson,但 Spring Boot 提供了另一种 @JsonComponent 注解,它使直接注册 Spring Bean 变得更加容易。

您可以直接在 JsonSerializerJsonDeserializerKeyDeserializer 实现上使用 @JsonComponent 注解。您也可以在包含序列化器/反序列化器作为内部类的类上使用它,如下面的示例所示

  • Java

  • Kotlin

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import org.springframework.boot.jackson.JsonComponent;

@JsonComponent
public class MyJsonComponent {

	public static class Serializer extends JsonSerializer<MyObject> {

		@Override
		public void serialize(MyObject value, JsonGenerator jgen, SerializerProvider serializers) throws IOException {
			jgen.writeStartObject();
			jgen.writeStringField("name", value.getName());
			jgen.writeNumberField("age", value.getAge());
			jgen.writeEndObject();
		}

	}

	public static class Deserializer extends JsonDeserializer<MyObject> {

		@Override
		public MyObject deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException {
			ObjectCodec codec = jsonParser.getCodec();
			JsonNode tree = codec.readTree(jsonParser);
			String name = tree.get("name").textValue();
			int age = tree.get("age").intValue();
			return new MyObject(name, age);
		}

	}

}
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.JsonSerializer
import com.fasterxml.jackson.databind.SerializerProvider
import org.springframework.boot.jackson.JsonComponent
import java.io.IOException

@JsonComponent
class MyJsonComponent {

	class Serializer : JsonSerializer<MyObject>() {
		@Throws(IOException::class)
		override fun serialize(value: MyObject, jgen: JsonGenerator, serializers: SerializerProvider) {
			jgen.writeStartObject()
			jgen.writeStringField("name", value.name)
			jgen.writeNumberField("age", value.age)
			jgen.writeEndObject()
		}
	}

	class Deserializer : JsonDeserializer<MyObject>() {
		@Throws(IOException::class, JsonProcessingException::class)
		override fun deserialize(jsonParser: JsonParser, ctxt: DeserializationContext): MyObject {
			val codec = jsonParser.codec
			val tree = codec.readTree<JsonNode>(jsonParser)
			val name = tree["name"].textValue()
			val age = tree["age"].intValue()
			return MyObject(name, age)
		}
	}

}

ApplicationContext 中的所有 @JsonComponent bean 会自动注册到 Jackson。由于 @JsonComponent 使用 @Component 进行元注解,因此通常的组件扫描规则适用。

Spring Boot 还提供了 JsonObjectSerializerJsonObjectDeserializer 基类,它们在序列化对象时提供了对标准 Jackson 版本的有用替代方案。有关详细信息,请参阅 Javadoc 中的 JsonObjectSerializerJsonObjectDeserializer

上面的示例可以改写为使用 JsonObjectSerializer/JsonObjectDeserializer,如下所示

  • Java

  • Kotlin

import java.io.IOException;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.ObjectCodec;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.SerializerProvider;

import org.springframework.boot.jackson.JsonComponent;
import org.springframework.boot.jackson.JsonObjectDeserializer;
import org.springframework.boot.jackson.JsonObjectSerializer;

@JsonComponent
public class MyJsonComponent {

	public static class Serializer extends JsonObjectSerializer<MyObject> {

		@Override
		protected void serializeObject(MyObject value, JsonGenerator jgen, SerializerProvider provider)
				throws IOException {
			jgen.writeStringField("name", value.getName());
			jgen.writeNumberField("age", value.getAge());
		}

	}

	public static class Deserializer extends JsonObjectDeserializer<MyObject> {

		@Override
		protected MyObject deserializeObject(JsonParser jsonParser, DeserializationContext context, ObjectCodec codec,
				JsonNode tree) throws IOException {
			String name = nullSafeValue(tree.get("name"), String.class);
			int age = nullSafeValue(tree.get("age"), Integer.class);
			return new MyObject(name, age);
		}

	}

}
/*
 * Copyright 2012-2022 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.boot.docs.features.json.jackson.customserializersanddeserializers.`object`

import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.core.ObjectCodec
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.SerializerProvider
import org.springframework.boot.jackson.JsonComponent
import org.springframework.boot.jackson.JsonObjectDeserializer
import org.springframework.boot.jackson.JsonObjectSerializer
import java.io.IOException

@JsonComponent
class MyJsonComponent {

	class Serializer : JsonObjectSerializer<MyObject>() {
		@Throws(IOException::class)
		override fun serializeObject(value: MyObject, jgen: JsonGenerator, provider: SerializerProvider) {
			jgen.writeStringField("name", value.name)
			jgen.writeNumberField("age", value.age)
		}
	}

	class Deserializer : JsonObjectDeserializer<MyObject>() {
		@Throws(IOException::class)
		override fun deserializeObject(jsonParser: JsonParser, context: DeserializationContext,
				codec: ObjectCodec, tree: JsonNode): MyObject {
			val name = nullSafeValue(tree["name"], String::class.java)
			val age = nullSafeValue(tree["age"], Int::class.java)
			return MyObject(name, age)
		}
	}

}

Mixins

Jackson 支持 mixins,它可以用来将额外的注解混合到目标类上已声明的注解中。Spring Boot 的 Jackson 自动配置将扫描您的应用程序包以查找使用 @JsonMixin 注解的类,并将它们注册到自动配置的 ObjectMapper 中。注册由 Spring Boot 的 JsonMixinModule 执行。

Gson

提供了 Gson 的自动配置。当 Gson 在类路径上时,会自动配置 Gson bean。提供了一些 spring.gson.* 配置属性用于自定义配置。要获得更多控制权,可以使用一个或多个 GsonBuilderCustomizer bean。

JSON-B

提供了 JSON-B 的自动配置。当 JSON-B API 和实现都在类路径上时,会自动配置 Jsonb bean。首选的 JSON-B 实现是 Eclipse Yasson,为此提供了依赖项管理。