Convert Hashmap to JSON object in Java (#14110)

This commit is for Convert Hashmap to JSON object in Java
This commit is contained in:
Bahaa El-Din Helmy 2023-05-24 03:05:20 +03:00 committed by GitHub
parent df15627edc
commit 05a672410d
1 changed files with 33 additions and 42 deletions

View File

@ -17,16 +17,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
public class MapToJsonUnitTest { public class MapToJsonUnitTest {
final TypeAdapter<JsonElement> strictAdapter = new Gson().getAdapter(JsonElement.class); String originalJsonData = "{\"CS\":\"Post1\",\"Linux\":\"Post1\",\"Kotlin\":\"Post1\"}";
public boolean isValid(String json) {
try {
strictAdapter.fromJson(json);
} catch (JsonSyntaxException | IOException e) {
return false;
}
return true;
}
@Test @Test
public void given_HashMapData_whenUsingJackson_thenConvertToJson() throws JsonProcessingException { public void given_HashMapData_whenUsingJackson_thenConvertToJson() throws JsonProcessingException {
@ -36,7 +27,7 @@ public class MapToJsonUnitTest {
data.put("Kotlin", "Post1"); data.put("Kotlin", "Post1");
ObjectMapper objectMapper = new ObjectMapper(); ObjectMapper objectMapper = new ObjectMapper();
String jacksonData = objectMapper.writeValueAsString(data); String jacksonData = objectMapper.writeValueAsString(data);
Assertions.assertTrue(isValid(jacksonData)); Assertions.assertEquals(jacksonData,originalJsonData);
} }
@Test @Test
@ -49,7 +40,7 @@ public class MapToJsonUnitTest {
Type typeObject = new TypeToken<HashMap>() { Type typeObject = new TypeToken<HashMap>() {
}.getType(); }.getType();
String gsonData = gson.toJson(data, typeObject); String gsonData = gson.toJson(data, typeObject);
Assertions.assertTrue(isValid(gsonData)); Assertions.assertEquals(gsonData,originalJsonData);
} }
@Test @Test
@ -60,6 +51,6 @@ public class MapToJsonUnitTest {
data.put("Kotlin", "Post1"); data.put("Kotlin", "Post1");
JSONObject jsonObject = new JSONObject(data); JSONObject jsonObject = new JSONObject(data);
String orgJsonData = jsonObject.toString(); String orgJsonData = jsonObject.toString();
Assertions.assertTrue(isValid(orgJsonData)); Assertions.assertEquals(orgJsonData,originalJsonData);
} }
} }