forked from json-iterator/java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTestCustomizeType.java
More file actions
78 lines (66 loc) · 2.49 KB
/
TestCustomizeType.java
File metadata and controls
78 lines (66 loc) · 2.49 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.jsoniter;
import junit.framework.TestCase;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Date;
public class TestCustomizeType extends TestCase {
public static class MyDate {
Date date;
}
static {
// JsonIterator.enableStrictMode();
JsonIterator.registerTypeDecoder(MyDate.class, new Decoder() {
@Override
public Object decode(final JsonIterator iter) throws IOException {
return new MyDate(){{
date = new Date(iter.readLong());
}};
}
});
}
public void test_direct() throws IOException {
JsonIterator iter = JsonIterator.parse("1481365190000");
MyDate date = iter.read(MyDate.class);
assertEquals(1481365190000L, date.date.getTime());
}
public static class FieldWithMyDate {
public MyDate field;
}
public void test_as_field_type() throws IOException {
JsonIterator iter = JsonIterator.parse("{'field': 1481365190000}".replace('\'', '"'));
FieldWithMyDate obj = iter.read(FieldWithMyDate.class);
assertEquals(1481365190000L, obj.field.date.getTime());
}
public void test_as_array_element() throws IOException {
JsonIterator iter = JsonIterator.parse("[1481365190000]");
MyDate[] dates = iter.read(MyDate[].class);
assertEquals(1481365190000L, dates[0].date.getTime());
}
public static class MyDate2 {
Date date;
}
public static class FieldWithMyDate2 {
public MyDate2 field;
}
public void test_customize_through_extension() throws IOException {
JsonIterator.registerExtension(new EmptyExtension() {
@Override
public Decoder createDecoder(Type type, Type... typeArgs) {
if (type == MyDate2.class) {
return new Decoder() {
@Override
public Object decode(final JsonIterator iter) throws IOException {
return new MyDate2(){{
date = new Date(iter.readLong());
}};
}
};
}
return null;
}
});
JsonIterator iter = JsonIterator.parse("{'field': 1481365190000}".replace('\'', '"'));
FieldWithMyDate2 obj = iter.read(FieldWithMyDate2.class);
assertEquals(1481365190000L, obj.field.date.getTime());
}
}