1+ package com .baeldung .gson .json ;
2+
3+ import com .google .gson .JsonObject ;
4+ import com .google .gson .JsonParser ;
5+ import org .junit .jupiter .api .Test ;
6+
7+ import java .util .List ;
8+
9+ import static org .junit .jupiter .api .Assertions .*;
10+
11+ public class JsonKeyExtractorUnitTest {
12+
13+ @ Test
14+ void givenJson_whenTopLevelKeys_thenGetAllKeys () {
15+ String json =
"{ \" name\" :\" Henry\" , \" email\" :\" [email protected] \" , \" age\" :25 }" ;
16+ JsonObject jsonObject = JsonParser .parseString (json ).getAsJsonObject ();
17+ List <String > keys = JsonKeyExtractor .getAllKeys (jsonObject );
18+
19+ assertEquals (3 , keys .size ());
20+ assertTrue (keys .contains ("name" ));
21+ assertTrue (keys .contains ("email" ));
22+ assertTrue (keys .contains ("age" ));
23+ }
24+
25+ @ Test
26+ void givenJson_whenNestedKeys_thenGetAllKeys () {
27+ String json = "{ \" address\" : { \" city\" :\" New York\" , \" zip\" :\" 10001\" } }" ;
28+ JsonObject jsonObject = JsonParser .parseString (json ).getAsJsonObject ();
29+ List <String > keys = JsonKeyExtractor .getAllKeys (jsonObject );
30+
31+ assertEquals (3 , keys .size ());
32+ assertTrue (keys .contains ("address" ));
33+ assertTrue (keys .contains ("address.city" ));
34+ assertTrue (keys .contains ("address.zip" ));
35+ }
36+
37+ @ Test
38+ void givenJson_whenEmpty_thenGetNoKeys () {
39+ String json = "{}" ;
40+ JsonObject jsonObject = JsonParser .parseString (json ).getAsJsonObject ();
41+ List <String > keys = JsonKeyExtractor .getAllKeys (jsonObject );
42+
43+ assertTrue (keys .isEmpty ());
44+ }
45+
46+ @ Test
47+ void givenJson_whenDeeplyNestedKeys_thenGetAllKeys () {
48+ String json =
"{ \" user\" : { \" profile\" : { \" contacts\" : { \" email\" : \" [email protected] \" } } } }" ;
49+ JsonObject jsonObject = JsonParser .parseString (json ).getAsJsonObject ();
50+ List <String > keys = JsonKeyExtractor .getAllKeys (jsonObject );
51+
52+ assertTrue (keys .contains ("user" ));
53+ assertTrue (keys .contains ("user.profile" ));
54+ assertTrue (keys .contains ("user.profile.contacts" ));
55+ assertTrue (keys .contains ("user.profile.contacts.email" ));
56+ }
57+ }
0 commit comments