|
1 | 1 | package de.agilecoders.wicket.jquery.util;
|
2 | 2 |
|
| 3 | +import com.fasterxml.jackson.core.JsonProcessingException; |
3 | 4 | import com.fasterxml.jackson.databind.JavaType;
|
4 | 5 | import com.fasterxml.jackson.databind.JsonNode;
|
5 | 6 | import com.fasterxml.jackson.databind.ObjectMapper;
|
@@ -31,6 +32,23 @@ private Json() {
|
31 | 32 | throw new UnsupportedOperationException();
|
32 | 33 | }
|
33 | 34 |
|
| 35 | + /** |
| 36 | + * Convert a string to a Java value |
| 37 | + * |
| 38 | + * @param json Json value to convert. |
| 39 | + * @param type Expected Java value type. |
| 40 | + * @param <T> type of return object |
| 41 | + * @return casted value of given json object |
| 42 | + * @throws ParseException to runtime if json node can't be casted to clazz. |
| 43 | + */ |
| 44 | + public static <T> T fromJson(final String json, final JavaType type) { |
| 45 | + try { |
| 46 | + return createObjectMapper().readValue(json, type); |
| 47 | + } catch (Exception e) { |
| 48 | + throw new ParseException(e); |
| 49 | + } |
| 50 | + } |
| 51 | + |
34 | 52 | /**
|
35 | 53 | * @return a new {@link ObjectMapper} instance which allows single
|
36 | 54 | * quotes and unquoted keys by default
|
@@ -75,23 +93,6 @@ public static <T> T fromJson(final JsonNode json, final Class<T> clazz) {
|
75 | 93 | }
|
76 | 94 | }
|
77 | 95 |
|
78 |
| - /** |
79 |
| - * Convert a string to a Java value |
80 |
| - * |
81 |
| - * @param json Json value to convert. |
82 |
| - * @param type Expected Java value type. |
83 |
| - * @param <T> type of return object |
84 |
| - * @return casted value of given json object |
85 |
| - * @throws ParseException to runtime if json node can't be casted to clazz. |
86 |
| - */ |
87 |
| - public static <T> T fromJson(final String json, final JavaType type) { |
88 |
| - try { |
89 |
| - return createObjectMapper().readValue(json, type); |
90 |
| - } catch (Exception e) { |
91 |
| - throw new ParseException(e); |
92 |
| - } |
93 |
| - } |
94 |
| - |
95 | 96 | /**
|
96 | 97 | * Convert a JsonNode to a Java value
|
97 | 98 | *
|
@@ -121,7 +122,11 @@ public static ObjectNode newObject() {
|
121 | 122 | * @return stringified version of given json object
|
122 | 123 | */
|
123 | 124 | public static String stringify(final JsonNode json) {
|
124 |
| - return json != null ? json.toString() : "{}"; |
| 125 | + try { |
| 126 | + return json != null ? createObjectMapper().writeValueAsString(json) : "{}"; |
| 127 | + } catch (JsonProcessingException jpx) { |
| 128 | + throw new RuntimeException("A problem occurred while stringifying a JsonNode: " + jpx.getMessage(), jpx); |
| 129 | + } |
125 | 130 | }
|
126 | 131 |
|
127 | 132 | /**
|
|
0 commit comments