BAEL-2738 - Convert String to JsonObject with GSON (#6318)

* BAEL-2738 - Convert String to JsonObject with GSON

* BAEL-2738 Assertions added in example 2 (Using fromJson)

* Update gson/src/test/java/org/baeldung/gson/conversion/JsonObjectConversionsUnitTest.java

Rename test name

Co-Authored-By: dcalap <dcalap@gmail.com>

* Update gson/src/test/java/org/baeldung/gson/conversion/JsonObjectConversionsUnitTest.java

Rename test

Co-Authored-By: dcalap <dcalap@gmail.com>

* Blank spaces added in order to separate given/when/then parts of the test
This commit is contained in:
dcalap 2019-02-23 14:37:02 +01:00 committed by KevinGilmore
parent ed427464ad
commit c2a300baae
1 changed files with 33 additions and 0 deletions

View File

@ -0,0 +1,33 @@
package org.baeldung.gson.conversion;
import com.google.gson.*;
import org.junit.Assert;
import org.junit.jupiter.api.Test;
public class JsonObjectConversionsUnitTest {
@Test
void whenUsingJsonParser_thenConvertToJsonObject() throws Exception {
// Example 1: Using JsonParser
String json = "{ \"name\": \"Baeldung\", \"java\": true }";
JsonObject jsonObject = new JsonParser().parse(json).getAsJsonObject();
Assert.assertTrue(jsonObject.isJsonObject());
Assert.assertTrue(jsonObject.get("name").getAsString().equals("Baeldung"));
Assert.assertTrue(jsonObject.get("java").getAsBoolean() == true);
}
@Test
void whenUsingGsonInstanceFromJson_thenConvertToJsonObject() throws Exception {
// Example 2: Using fromJson
String json = "{ \"name\": \"Baeldung\", \"java\": true }";
JsonObject convertedObject = new Gson().fromJson(json, JsonObject.class);
Assert.assertTrue(convertedObject.isJsonObject());
Assert.assertTrue(convertedObject.get("name").getAsString().equals("Baeldung"));
Assert.assertTrue(convertedObject.get("java").getAsBoolean() == true);
}
}