Skip to content

Commit

Permalink
BAEL-2738 - Convert String to JsonObject with GSON (eugenp#6318)
Browse files Browse the repository at this point in the history
* 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 <[email protected]>

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

Rename test

Co-Authored-By: dcalap <[email protected]>

* Blank spaces added in order to separate given/when/then parts of the test
  • Loading branch information
dcalap authored and KevinGilmore committed Feb 23, 2019
1 parent ed42746 commit c2a300b
Showing 1 changed file with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -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);
}

}

0 comments on commit c2a300b

Please sign in to comment.