Skip to content

Commit 521e2e6

Browse files
committed
feat(json): Add parsing support
1 parent c06a408 commit 521e2e6

File tree

6 files changed

+1003
-1
lines changed

6 files changed

+1003
-1
lines changed

components/json/src/main/java/datadog/json/JsonMapper.java

+49
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
package datadog.json;
22

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;
38
import java.util.Collection;
9+
import java.util.List;
410
import java.util.Map;
511

612
/** Utility class for simple Java structure mapping into JSON strings. */
@@ -103,4 +109,47 @@ public static String toJson(String[] items) {
103109
return writer.toString();
104110
}
105111
}
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+
}
106155
}

0 commit comments

Comments
 (0)