|
1 | 1 | package datadog.json;
|
2 | 2 |
|
| 3 | +import static java.util.Collections.emptyList; |
| 4 | +import static java.util.Collections.emptyMap; |
| 5 | + |
| 6 | +import java.io.IOException; |
| 7 | +import java.util.ArrayList; |
3 | 8 | import java.util.Collection;
|
| 9 | +import java.util.List; |
4 | 10 | import java.util.Map;
|
5 | 11 |
|
6 | 12 | /** Utility class for simple Java structure mapping into JSON strings. */
|
@@ -103,4 +109,47 @@ public static String toJson(String[] items) {
|
103 | 109 | return writer.toString();
|
104 | 110 | }
|
105 | 111 | }
|
| 112 | + |
| 113 | + /** |
| 114 | + * Parses a JSON string into a {@link Map}. |
| 115 | + * |
| 116 | + * @param json The JSON string to parse. |
| 117 | + * @return A {@link Map} containing the parsed JSON object's key-value pairs. |
| 118 | + * @throws IOException If the JSON is invalid or a reader error occurs. |
| 119 | + */ |
| 120 | + @SuppressWarnings("unchecked") |
| 121 | + public static Map<String, Object> fromJsonToMap(String json) throws IOException { |
| 122 | + if (json == null || json.isEmpty() || "{}".equals(json) || "null".equals(json)) { |
| 123 | + return emptyMap(); |
| 124 | + } |
| 125 | + try (JsonReader reader = new JsonReader(json)) { |
| 126 | + Object value = reader.nextValue(); |
| 127 | + if (!(value instanceof Map)) { |
| 128 | + throw new IOException("Expected JSON object but was " + value.getClass().getSimpleName()); |
| 129 | + } |
| 130 | + return (Map<String, Object>) value; |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + /** |
| 135 | + * Parses a JSON string array into a {@link List<String>}. |
| 136 | + * |
| 137 | + * @param json The JSON string array to parse. |
| 138 | + * @return A {@link List<String>} containing the parsed JSON strings. |
| 139 | + * @throws IOException If the JSON is invalid or a reader error occurs. |
| 140 | + */ |
| 141 | + public static List<String> fromJsonToList(String json) throws IOException { |
| 142 | + if (json == null || json.isEmpty() || "[]".equals(json) || "null".equals(json)) { |
| 143 | + return emptyList(); |
| 144 | + } |
| 145 | + try (JsonReader reader = new JsonReader(json)) { |
| 146 | + List<String> list = new ArrayList<>(); |
| 147 | + reader.beginArray(); |
| 148 | + while (reader.hasNext()) { |
| 149 | + list.add(reader.nextString()); |
| 150 | + } |
| 151 | + reader.endArray(); |
| 152 | + return list; |
| 153 | + } |
| 154 | + } |
106 | 155 | }
|
0 commit comments