Skip to content

Commit 9a65fe4

Browse files
javier-godoypaodb
authored andcommitted
feat: add JsonCodec encodeWithoutTypeInfo
1 parent 295f183 commit 9a65fe4

File tree

1 file changed

+52
-1
lines changed

1 file changed

+52
-1
lines changed

src/main/java/com/flowingcode/vaadin/jsonmigration/JsonCodec.java

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,10 @@
3636

3737
import com.vaadin.flow.component.Component;
3838
import com.vaadin.flow.dom.Element;
39+
import com.vaadin.flow.dom.Node;
3940
import com.vaadin.flow.internal.ReflectTools;
41+
import com.vaadin.flow.internal.nodefeature.ReturnChannelRegistration;
42+
import elemental.json.Json;
4043
import elemental.json.JsonType;
4144
import elemental.json.JsonValue;
4245

@@ -58,7 +61,7 @@
5861
* <p>
5962
* @author Vaadin Ltd
6063
*/
61-
class JsonCodec {
64+
public class JsonCodec {
6265

6366
/**
6467
* Decodes the given JSON value as the given type.
@@ -101,4 +104,52 @@ public static <T> T decodeAs(JsonValue json, Class<T> type) {
101104

102105
}
103106

107+
/**
108+
* Helper for checking whether the type is supported by
109+
* {@link #encodeWithoutTypeInfo(Object)}. Supported value types are
110+
* {@link String}, {@link Integer}, {@link Double}, {@link Boolean},
111+
* {@link JsonValue}.
112+
*
113+
* @param type
114+
* the type to check
115+
* @return whether the type can be encoded
116+
*/
117+
public static boolean canEncodeWithoutTypeInfo(Class<?> type) {
118+
assert type != null;
119+
return String.class.equals(type) || Integer.class.equals(type)
120+
|| Double.class.equals(type) || Boolean.class.equals(type)
121+
|| JsonValue.class.isAssignableFrom(type);
122+
}
123+
124+
/**
125+
* Helper for encoding any "primitive" value that is directly supported in
126+
* JSON. Supported values types are {@link String}, {@link Number},
127+
* {@link Boolean}, {@link JsonValue}. <code>null</code> is also supported.
128+
*
129+
* @param value
130+
* the value to encode
131+
* @return the value encoded as JSON
132+
*/
133+
public static JsonValue encodeWithoutTypeInfo(Object value) {
134+
if (value == null) {
135+
return Json.createNull();
136+
}
137+
138+
assert canEncodeWithoutTypeInfo(value.getClass());
139+
140+
Class<?> type = value.getClass();
141+
if (String.class.equals(value.getClass())) {
142+
return Json.create((String) value);
143+
} else if (Integer.class.equals(type) || Double.class.equals(type)) {
144+
return Json.create(((Number) value).doubleValue());
145+
} else if (Boolean.class.equals(type)) {
146+
return Json.create(((Boolean) value).booleanValue());
147+
} else if (JsonValue.class.isAssignableFrom(type)) {
148+
return (JsonValue) value;
149+
}
150+
assert !canEncodeWithoutTypeInfo(type);
151+
throw new IllegalArgumentException(
152+
"Can't encode " + value.getClass() + " to json");
153+
}
154+
104155
}

0 commit comments

Comments
 (0)