|
| 1 | +/* |
| 2 | + * Copyright 2002-2020 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +package org.springframework.http.converter.json; |
| 18 | + |
| 19 | +import java.io.IOException; |
| 20 | +import java.lang.reflect.Type; |
| 21 | +import java.nio.charset.Charset; |
| 22 | +import java.nio.charset.StandardCharsets; |
| 23 | +import java.util.Map; |
| 24 | + |
| 25 | +import kotlinx.serialization.KSerializer; |
| 26 | +import kotlinx.serialization.SerializationException; |
| 27 | +import kotlinx.serialization.SerializersKt; |
| 28 | +import kotlinx.serialization.json.Json; |
| 29 | + |
| 30 | +import org.springframework.http.HttpInputMessage; |
| 31 | +import org.springframework.http.HttpOutputMessage; |
| 32 | +import org.springframework.http.MediaType; |
| 33 | +import org.springframework.http.converter.AbstractGenericHttpMessageConverter; |
| 34 | +import org.springframework.http.converter.HttpMessageNotReadableException; |
| 35 | +import org.springframework.http.converter.HttpMessageNotWritableException; |
| 36 | +import org.springframework.lang.Nullable; |
| 37 | +import org.springframework.util.ConcurrentReferenceHashMap; |
| 38 | +import org.springframework.util.StreamUtils; |
| 39 | + |
| 40 | +/** |
| 41 | + * Implementation of {@link org.springframework.http.converter.HttpMessageConverter} that can read and write JSON using |
| 42 | + * <a href="https://github.com/Kotlin/kotlinx.serialization">kotlinx.serialization</a>. |
| 43 | + * |
| 44 | + * <p>This converter can be used to bind {@code @Serializable} Kotlin classes. It supports {@code application/json} and |
| 45 | + * {@code application/*+json} with various character sets, {@code UTF-8} being the default. |
| 46 | + * |
| 47 | + * @author Andreas Ahlenstorf |
| 48 | + * @author Sebastien Deleuze |
| 49 | + * @since 5.3 |
| 50 | + */ |
| 51 | +public class KotlinSerializationJsonHttpMessageConverter extends AbstractGenericHttpMessageConverter<Object> { |
| 52 | + |
| 53 | + private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; |
| 54 | + |
| 55 | + private static final Map<Type, KSerializer<Object>> serializerCache = new ConcurrentReferenceHashMap<>(); |
| 56 | + |
| 57 | + private final Json json; |
| 58 | + |
| 59 | + /** |
| 60 | + * Construct a new {@code KotlinSerializationJsonHttpMessageConverter} with the default configuration. |
| 61 | + */ |
| 62 | + public KotlinSerializationJsonHttpMessageConverter() { |
| 63 | + this(Json.Default); |
| 64 | + } |
| 65 | + |
| 66 | + /** |
| 67 | + * Construct a new {@code KotlinSerializationJsonHttpMessageConverter} with a custom configuration. |
| 68 | + */ |
| 69 | + public KotlinSerializationJsonHttpMessageConverter(Json json) { |
| 70 | + super(MediaType.APPLICATION_JSON, new MediaType("application", "*+json")); |
| 71 | + this.json = json; |
| 72 | + } |
| 73 | + |
| 74 | + @Override |
| 75 | + protected boolean supports(Class<?> clazz) { |
| 76 | + try { |
| 77 | + resolve(clazz); |
| 78 | + return true; |
| 79 | + } |
| 80 | + catch (Exception ex) { |
| 81 | + return false; |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + @Override |
| 86 | + protected Object readInternal(Class<?> clazz, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { |
| 87 | + return this.read(clazz, null, inputMessage); |
| 88 | + } |
| 89 | + |
| 90 | + @Override |
| 91 | + public Object read(Type type, @Nullable Class<?> contextClass, HttpInputMessage inputMessage) throws IOException, HttpMessageNotReadableException { |
| 92 | + MediaType contentType = inputMessage.getHeaders().getContentType(); |
| 93 | + String jsonText = StreamUtils.copyToString(inputMessage.getBody(), getCharsetToUse(contentType)); |
| 94 | + try { |
| 95 | + // TODO Use stream based API when available |
| 96 | + return this.json.decodeFromString(resolve(type), jsonText); |
| 97 | + } |
| 98 | + catch (SerializationException ex) { |
| 99 | + throw new HttpMessageNotReadableException("Could not read JSON: " + ex.getMessage(), ex, inputMessage); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + @Override |
| 104 | + protected void writeInternal(Object o, HttpOutputMessage outputMessage) throws HttpMessageNotWritableException { |
| 105 | + try { |
| 106 | + this.writeInternal(o, o.getClass(), outputMessage); |
| 107 | + } |
| 108 | + catch (IOException ex) { |
| 109 | + throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + @Override |
| 114 | + protected void writeInternal(Object o, @Nullable Type type, HttpOutputMessage outputMessage) throws IOException, HttpMessageNotWritableException { |
| 115 | + try { |
| 116 | + String json = this.json.encodeToString(resolve(type), o); |
| 117 | + MediaType contentType = outputMessage.getHeaders().getContentType(); |
| 118 | + outputMessage.getBody().write(json.getBytes(getCharsetToUse(contentType))); |
| 119 | + outputMessage.getBody().flush(); |
| 120 | + } |
| 121 | + catch (IOException ex) { |
| 122 | + throw ex; |
| 123 | + } |
| 124 | + catch (Exception ex) { |
| 125 | + throw new HttpMessageNotWritableException("Could not write JSON: " + ex.getMessage(), ex); |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + private Charset getCharsetToUse(@Nullable MediaType contentType) { |
| 130 | + if (contentType != null && contentType.getCharset() != null) { |
| 131 | + return contentType.getCharset(); |
| 132 | + } |
| 133 | + return DEFAULT_CHARSET; |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * Tries to find a serializer that can marshall or unmarshall instances of the given type using |
| 138 | + * kotlinx.serialization. If no serializer can be found, an exception is thrown. |
| 139 | + * <p> |
| 140 | + * Resolved serializers are cached and cached results are returned on successive calls. |
| 141 | + * |
| 142 | + * @param type to find a serializer for. |
| 143 | + * @return resolved serializer for the given type. |
| 144 | + * @throws RuntimeException if no serializer supporting the given type can be found. |
| 145 | + */ |
| 146 | + private KSerializer<Object> resolve(Type type) { |
| 147 | + KSerializer<Object> serializer = serializerCache.get(type); |
| 148 | + if (serializer == null) { |
| 149 | + serializer = SerializersKt.serializer(type); |
| 150 | + serializerCache.put(type, serializer); |
| 151 | + } |
| 152 | + return serializer; |
| 153 | + } |
| 154 | +} |
0 commit comments