|
36 | 36 |
|
37 | 37 | import com.vaadin.flow.component.Component; |
38 | 38 | import com.vaadin.flow.dom.Element; |
| 39 | +import com.vaadin.flow.dom.Node; |
39 | 40 | import com.vaadin.flow.internal.ReflectTools; |
| 41 | +import com.vaadin.flow.internal.nodefeature.ReturnChannelRegistration; |
| 42 | +import elemental.json.Json; |
40 | 43 | import elemental.json.JsonType; |
41 | 44 | import elemental.json.JsonValue; |
42 | 45 |
|
|
58 | 61 | * <p> |
59 | 62 | * @author Vaadin Ltd |
60 | 63 | */ |
61 | | -class JsonCodec { |
| 64 | +public class JsonCodec { |
62 | 65 |
|
63 | 66 | /** |
64 | 67 | * Decodes the given JSON value as the given type. |
@@ -101,4 +104,52 @@ public static <T> T decodeAs(JsonValue json, Class<T> type) { |
101 | 104 |
|
102 | 105 | } |
103 | 106 |
|
| 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 | + |
104 | 155 | } |
0 commit comments