Convert Hashmap to JSON object in Java (#14118)

This commit is related to the article "Convert Hashmap to JSON object in Java"
This commit is contained in:
Bahaa El-Din Helmy 2023-05-26 03:45:29 +03:00 committed by GitHub
parent 4bd81b7271
commit 296be923ce
1 changed files with 33 additions and 33 deletions

View File

@ -17,40 +17,40 @@ import java.util.HashMap;
import java.util.Map;
public class MapToJsonUnitTest {
String originalJsonData = "{\"CS\":\"Post1\",\"Linux\":\"Post1\",\"Kotlin\":\"Post1\"}";
String originalJsonData = "{\"CS\":\"Post1\",\"Linux\":\"Post1\",\"Kotlin\":\"Post1\"}";
@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.assertEquals(originalJsonData,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.assertEquals(originalJsonData,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.assertEquals(orgJsonData,originalJsonData);
}
@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(originalJsonData,orgJsonData);
}
}