source: java2python/jackson-t/src/test/java/testcode/Value.java@ 451

Last change on this file since 451 was 418, checked in by wouter, 2 years ago

#126 added Value, ValueTest . This closely reflects using a custom deserializer whcih we need . The test is currently failing

File size: 2.1 KB
RevLine 
[418]1package testcode;
2
3import static org.junit.Assert.assertEquals;
4
5import java.io.IOException;
6import java.util.Objects;
7
8import com.fasterxml.jackson.core.JsonParser;
9import com.fasterxml.jackson.core.JsonProcessingException;
10import com.fasterxml.jackson.databind.DeserializationContext;
11import com.fasterxml.jackson.databind.ObjectMapper;
12import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
13import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
14
15@JsonDeserialize(using = ValueDeserializer.class)
16public class Value {
17 private final Object value;
18
19 public Value(Object value) {
20 this.value = value;
21 }
22
23 public Object getValue() {
24 return value;
25 }
26
27 /** The test code for Value */
28 public static void main(String[] args) throws JsonProcessingException {
29 ObjectMapper jackson = new ObjectMapper();
30 Value val = new Value((float) 12);
31 System.out.println(jackson.writeValueAsString(val));
32 assertEquals(val, jackson.readValue("12", Value.class));
33 val = new Value("hallo");
34 System.out.println(jackson.writeValueAsString(val));
35 assertEquals(val, jackson.readValue("\"hallo\"", Value.class));
36 }
37
38 @Override
39 public int hashCode() {
40 return Objects.hash(value);
41 }
42
43 @Override
44 public boolean equals(Object obj) {
45 if (this == obj)
46 return true;
47 if (obj == null)
48 return false;
49 if (getClass() != obj.getClass())
50 return false;
51 Value other = (Value) obj;
52 return Objects.equals(value, other.value);
53 }
54
55 @Override
56 public String toString() {
57 return "val:" + value;
58 }
59}
60
61class ValueDeserializer extends StdDeserializer<Value> {
62 public ValueDeserializer() {
63 this(null);
64 }
65
66 public ValueDeserializer(Class<?> vc) {
67 super(vc);
68 }
69
70 @Override
71 public Value deserialize(JsonParser jp, DeserializationContext ctxt)
72 throws IOException, JsonProcessingException {
73 String text = jp.getText();
74 switch (jp.currentToken()) {
75 case VALUE_NUMBER_FLOAT:
76 case VALUE_NUMBER_INT:
77 return new Value(Float.parseFloat(text));
78 case VALUE_STRING:
79 return new Value(text);
80 default:
81 throw new IOException(
82 "Expected number of double quoted string but found " + text
83 + " of type " + jp.currentToken());
84 }
85
86 }
87
88}
Note: See TracBrowser for help on using the repository browser.