-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
Expand file tree
/
Copy pathInetSocketAddressSerializer.java
More file actions
57 lines (50 loc) · 2.1 KB
/
Copy pathInetSocketAddressSerializer.java
File metadata and controls
57 lines (50 loc) · 2.1 KB
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
package com.fasterxml.jackson.databind.ser.std;
import java.io.IOException;
import java.net.*;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.core.type.WritableTypeId;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.jsontype.TypeSerializer;
/**
* Simple serializer for {@link InetSocketAddress}.
*/
@SuppressWarnings("serial")
public class InetSocketAddressSerializer
extends StdScalarSerializer<InetSocketAddress>
{
public InetSocketAddressSerializer() { super(InetSocketAddress.class); }
@Override
public void serialize(InetSocketAddress value, JsonGenerator g, SerializerProvider ctxt)
throws IOException
{
InetAddress addr = value.getAddress();
String str = addr == null ? value.getHostName() : addr.toString().trim();
int ix = str.indexOf('/');
if (ix >= 0) {
if (ix == 0) { // missing host name; use address
str = addr instanceof Inet6Address
? "[" + str.substring(1) + "]" // bracket IPv6 addresses with
: str.substring(1);
} else { // otherwise use name
str = str.substring(0, ix);
}
} else if (addr == null && str.indexOf(':') >= 0 && !str.startsWith("[")) {
// Unresolved address exposes no `InetAddress`, so an IPv6 literal has to be
// recognized from the host name; without brackets the port is not separable
str = "[" + str + "]";
}
g.writeString(str + ":" + value.getPort());
}
@Override
public void serializeWithType(InetSocketAddress value, JsonGenerator g,
SerializerProvider ctxt, TypeSerializer typeSer)
throws IOException
{
// Better ensure we don't use specific sub-classes...
WritableTypeId typeIdDef = typeSer.writeTypePrefix(g,
typeSer.typeId(value, InetSocketAddress.class, JsonToken.VALUE_STRING));
serialize(value, g, ctxt);
typeSer.writeTypeSuffix(g, typeIdDef);
}
}