/
Json.java
197 lines (173 loc) · 6.41 KB
/
Json.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
/*
* Copyright (c) 2011-2014 The original author or authors
* ------------------------------------------------------
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You may elect to redistribute this code under either of these licenses.
*/
package io.vertx.core.json;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import io.netty.buffer.ByteBufInputStream;
import io.vertx.core.buffer.Buffer;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.Instant;
import java.util.Base64;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import static java.time.format.DateTimeFormatter.ISO_INSTANT;
/**
* @author <a href="http://tfox.org">Tim Fox</a>
*/
public class Json {
public static ObjectMapper mapper = new ObjectMapper();
public static ObjectMapper prettyMapper = new ObjectMapper();
static {
// Non-standard JSON but we allow C style comments in our JSON
mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
prettyMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
prettyMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
SimpleModule module = new SimpleModule();
// custom types
module.addSerializer(JsonObject.class, new JsonObjectSerializer());
module.addSerializer(JsonArray.class, new JsonArraySerializer());
// he have 2 extensions: RFC-7493
module.addSerializer(Instant.class, new InstantSerializer());
module.addSerializer(byte[].class, new ByteArraySerializer());
mapper.registerModule(module);
prettyMapper.registerModule(module);
}
public static String encode(Object obj) throws EncodeException {
try {
return mapper.writeValueAsString(obj);
} catch (Exception e) {
throw new EncodeException("Failed to encode as JSON: " + e.getMessage());
}
}
public static Buffer encodeToBuffer(Object obj) throws EncodeException {
try {
return Buffer.buffer(mapper.writeValueAsBytes(obj));
} catch (Exception e) {
throw new EncodeException("Failed to encode as JSON: " + e.getMessage());
}
}
public static String encodePrettily(Object obj) throws EncodeException {
try {
return prettyMapper.writeValueAsString(obj);
} catch (Exception e) {
throw new EncodeException("Failed to encode as JSON: " + e.getMessage());
}
}
public static <T> T decodeValue(String str, Class<T> clazz) throws DecodeException {
try {
return mapper.readValue(str, clazz);
} catch (Exception e) {
throw new DecodeException("Failed to decode:" + e.getMessage());
}
}
public static <T> T decodeValue(String str, TypeReference<T> type) throws DecodeException {
try {
return mapper.readValue(str, type);
} catch (Exception e) {
throw new DecodeException("Failed to decode:" + e.getMessage(), e);
}
}
public static <T> T decodeValue(Buffer buf, Class<T> clazz) throws DecodeException {
return decodeValue(new ByteBufInputStream(buf.getByteBuf()), clazz);
}
public static <T> T decodeValue(InputStream stream, Class<T> clazz) throws DecodeException {
try {
return mapper.readValue(stream, clazz);
} catch (Exception e) {
throw new DecodeException("Failed to decode:" + e.getMessage(), e);
}
}
@SuppressWarnings("unchecked")
static Object checkAndCopy(Object val, boolean copy) {
if (val == null) {
// OK
} else if (val instanceof Number && !(val instanceof BigDecimal)) {
// OK
} else if (val instanceof Boolean) {
// OK
} else if (val instanceof String) {
// OK
} else if (val instanceof Character) {
// OK
} else if (val instanceof CharSequence) {
val = val.toString();
} else if (val instanceof JsonObject) {
if (copy) {
val = ((JsonObject) val).copy();
}
} else if (val instanceof JsonArray) {
if (copy) {
val = ((JsonArray) val).copy();
}
} else if (val instanceof Map) {
if (copy) {
val = (new JsonObject((Map)val)).copy();
} else {
val = new JsonObject((Map)val);
}
} else if (val instanceof List) {
if (copy) {
val = (new JsonArray((List)val)).copy();
} else {
val = new JsonArray((List)val);
}
} else if (val instanceof byte[]) {
val = Base64.getEncoder().encodeToString((byte[])val);
} else if (val instanceof Instant) {
val = ISO_INSTANT.format((Instant) val);
} else {
throw new IllegalStateException("Illegal type in JsonObject: " + val.getClass());
}
return val;
}
static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
Iterable<T> iterable = () -> sourceIterator;
return StreamSupport.stream(iterable.spliterator(), false);
}
private static class JsonObjectSerializer extends JsonSerializer<JsonObject> {
@Override
public void serialize(JsonObject value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeObject(value.getMap());
}
}
private static class JsonArraySerializer extends JsonSerializer<JsonArray> {
@Override
public void serialize(JsonArray value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeObject(value.getList());
}
}
private static class InstantSerializer extends JsonSerializer<Instant> {
@Override
public void serialize(Instant value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeString(ISO_INSTANT.format(value));
}
}
private static class ByteArraySerializer extends JsonSerializer<byte[]> {
private final Base64.Encoder BASE64 = Base64.getEncoder();
@Override
public void serialize(byte[] value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
jgen.writeString(BASE64.encodeToString(value));
}
}
}