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,49 +17,40 @@ import java.util.HashMap;
import java.util.Map;
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
public void given_HashMapData_whenUsingJackson_thenConvertToJson() throws JsonProcessingException {
Map<String, String> data = new HashMap();
data.put("CS", "Post1");
data.put("Linux", "Post1");
data.put("Kotlin", "Post1");
ObjectMapper objectMapper = new ObjectMapper();
String jacksonData = objectMapper.writeValueAsString(data);
Assertions.assertEquals(jacksonData,originalJsonData);
}
@Test
public void given_HashMapData_whenUsingJackson_thenConvertToJson() throws JsonProcessingException {
Map<String, String> data = new HashMap();
data.put("CS", "Post1");
data.put("Linux", "Post1");
data.put("Kotlin", "Post1");
ObjectMapper objectMapper = new ObjectMapper();
String jacksonData = objectMapper.writeValueAsString(data);
Assertions.assertTrue(isValid(jacksonData));
}
@Test
public void given_HashMapData_whenUsingGson_thenConvertToJson() {
Map<String, String> data = new HashMap<>();
data.put("CS", "Post1");
data.put("Linux", "Post1");
data.put("Kotlin", "Post1");
Gson gson = new Gson();
Type typeObject = new TypeToken<HashMap>() {
}.getType();
String gsonData = gson.toJson(data, typeObject);
Assertions.assertEquals(gsonData,originalJsonData);
}
@Test
public void given_HashMapData_whenUsingGson_thenConvertToJson() {
Map<String, String> data = new HashMap<>();
data.put("CS", "Post1");
data.put("Linux", "Post1");
data.put("Kotlin", "Post1");
Gson gson = new Gson();
Type typeObject = new TypeToken<HashMap>() {
}.getType();
String gsonData = gson.toJson(data, typeObject);
Assertions.assertTrue(isValid(gsonData));
}
@Test
public void given_HashMapData_whenOrgJson_thenConvertToJsonUsing() {
Map<String, String> data = new HashMap<>();
data.put("CS", "Post1");
data.put("Linux", "Post1");
data.put("Kotlin", "Post1");
JSONObject jsonObject = new JSONObject(data);
String orgJsonData = jsonObject.toString();
Assertions.assertTrue(isValid(orgJsonData));
}
@Test
public void given_HashMapData_whenOrgJson_thenConvertToJsonUsing() {
Map<String, String> data = new HashMap<>();
data.put("CS", "Post1");
data.put("Linux", "Post1");
data.put("Kotlin", "Post1");
JSONObject jsonObject = new JSONObject(data);
String orgJsonData = jsonObject.toString();
Assertions.assertEquals(orgJsonData,originalJsonData);
}
}