You can convert it to a JavaBean if you want using:

 Gson gson = new GsonBuilder().setPrettyPrinting().create();
 gson.fromJson(jsonString, JavaBean.class)

To use JsonObject, which is more flexible, use the following:

String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}";
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(json);
Assert.assertNotNull(jo);
Assert.assertTrue(jo.get("Success").getAsString());

Which is equivalent to the following:

JsonElement jelem = gson.fromJson(json, JsonElement.class);
JsonObject jobj = jelem.getAsJsonObject();
Answer from eadjei on Stack Overflow
🌐
GitHub
google.github.io › gson › UserGuide.html
Gson User Guide | gson
Gson gson = new Gson(); int[] ints = {1, 2, 3, 4, 5}; String[] strings = {"abc", "def", "ghi"}; // Serialization gson.toJson(ints); // ==> [1,2,3,4,5] gson.toJson(strings); // ==> ["abc", "def", "ghi"] // Deserialization int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); // ==> ints2 will be same as ints ·
Discussions

Help with using Gson to convert simple JSON string to Java object
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
10
0
July 28, 2022
java - Gson: Directly convert String to JsonObject (no POJO) - Stack Overflow
Can't seem to figure this out. I'm attempting JSON tree manipulation in GSON, but I have a case where I do not know or have a POJO to convert a string into, prior to converting to JsonObject. Is th... More on stackoverflow.com
🌐 stackoverflow.com
Strings with characters " and \ causing issues when parsing to class using fromJSON
Gson version 2.10 Java / Android version openjdk version "17.0.3" Used tools Maven; version: Apache Maven 3.8.5 Description When using fromJSON to parse JSON into a class with a String me... More on github.com
🌐 github.com
2
November 25, 2022
java - GSON - Get JSON value from String - Stack Overflow
I'm trying to parse the JSON String "{'test': '100.00'}" and in order to get the value: 100.00 with the GSON library. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Baeldung
baeldung.com › home › json › convert string to jsonobject with gson
Convert String to JsonObject with Gson | Baeldung
May 5, 2025 - In this tutorial, we’ll learn how Gson can give us a JsonObject from a String.
🌐
Mkyong
mkyong.com › home › java › convert java objects to from json using gson
Convert Java objects to from JSON using Gson - Mkyong.com
May 6, 2024 - Gson gson = new Gson(); // A Java object Staff obj = new Staff(); // Converts Java object to JSON string String json = gson.toJson(obj); // Converts Java object to File try (Writer writer = new FileWriter("staff.json")) { gson.toJson(staff, writer); } catch (IOException e) { throw new RuntimeException(e); } Converts JSON to Java objects using gson.fromJson().

You can convert it to a JavaBean if you want using:

 Gson gson = new GsonBuilder().setPrettyPrinting().create();
 gson.fromJson(jsonString, JavaBean.class)

To use JsonObject, which is more flexible, use the following:

String json = "{\"Success\":true,\"Message\":\"Invalid access token.\"}";
JsonParser jsonParser = new JsonParser();
JsonObject jo = (JsonObject)jsonParser.parse(json);
Assert.assertNotNull(jo);
Assert.assertTrue(jo.get("Success").getAsString());

Which is equivalent to the following:

JsonElement jelem = gson.fromJson(json, JsonElement.class);
JsonObject jobj = jelem.getAsJsonObject();
Answer from eadjei on Stack Overflow
🌐
Reddit
reddit.com › r/javahelp › help with using gson to convert simple json string to java object
r/javahelp on Reddit: Help with using Gson to convert simple JSON string to Java object
July 28, 2022 -

I'm new to Java but I have experience with Python and Swift so I'm familiar with the concept of creating custom objects to decode json.

I've been at this for hours looking at tons of documentation and tutorial pages and nothing has fixed the issue.

JsonTest.java

package com.joerex.httpjson;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

public class JsonTest {

	public static void main(String[] args) {
		
		GsonBuilder gsonBuilder = new GsonBuilder();
		Gson gson = gsonBuilder.create();
		
		String jsonString = "{'favoriteColor':'blue'}";
		
//		JsonElement jsonElem = JsonParser.parseString(jsonString);
//		JsonObject jsonObj = jsonElem.getAsJsonObject();
		
                // code breaks here
		var favColor = gson.fromJson(jsonString, FavoriteColor.class);
		
		System.out.println(favColor);
		
	}
	


}

FavoriteColor.java

package com.joerex.httpjson;

public class FavoriteColor {
	public String favoriteColor;
}

Here's the error message I'm getting -

Exception in thread "main" com.google.gson.JsonIOException: Failed making field 'com.joerex.httpjson.FavoriteColor#favoriteColor' accessible; either change its visibility or write a custom TypeAdapter for its declaring type
	at com.google.gson@2.9.0/com.google.gson.internal.reflect.ReflectionHelper.makeAccessible(ReflectionHelper.java:22)
	at com.google.gson@2.9.0/com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:158)
	at com.google.gson@2.9.0/com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:101)
	at com.google.gson@2.9.0/com.google.gson.Gson.getAdapter(Gson.java:501)
	at com.google.gson@2.9.0/com.google.gson.Gson.fromJson(Gson.java:990)
	at com.google.gson@2.9.0/com.google.gson.Gson.fromJson(Gson.java:956)
	at com.google.gson@2.9.0/com.google.gson.Gson.fromJson(Gson.java:905)
	at com.google.gson@2.9.0/com.google.gson.Gson.fromJson(Gson.java:876)
	at HelloWorld/com.joerex.httpjson.JsonTest.main(JsonTest.java:33)
Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field public java.lang.String com.joerex.httpjson.FavoriteColor.favoriteColor accessible: module HelloWorld does not "exports com.joerex.httpjson" to module com.google.gson
	at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:340)
	at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:280)
	at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:176)
	at java.base/java.lang.reflect.Field.setAccessible(Field.java:170)
	at com.google.gson@2.9.0/com.google.gson.internal.reflect.ReflectionHelper.makeAccessible(ReflectionHelper.java:19)
	... 8 more

EDIT:

SOLVED! The issue was my in my module-info.java file which I did not include in my original post. Needed to open up my module to the Gson module. I still don't completely understand why - cause I thought making a class "public" would be enough

module com.joerex.httpjson {
	exports com.joerex.httpjson;
	
	opens com.joerex.httpjson to com.google.gson;
	
	requires com.google.gson;
	requires java.net.http;
}

Top answer
1 of 3
1
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://imgur.com/a/fgoFFis ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.
2 of 3
1
try adding the setter method for favorite color in the favourite colour class. Not sure if Gson works with public properties. Ohhh, nvm. The error message states that your module is not exported. Can't help you with that, but you should able to google it from here
🌐
GitHub
github.com › google › gson
GitHub - google/gson: A Java serialization/deserialization library to convert Java Objects into JSON and back · GitHub
This avoids Gson's runtime crashes when optimizations are applied (usually due to the fields missing or being obfuscated), and results in faster performance on Android devices. The Moshi APIs may be more familiar to users who already know Gson. If you still want to use Gson and attempt to avoid these crashes, you can see how to do so here. Provide simple toJson() and fromJson() methods to convert Java objects to JSON and vice-versa
Starred by 24.4K users
Forked by 4.4K users
Languages   Java
🌐
Mkyong
mkyong.com › home › java › how to parse json using gson
How to parse JSON using Gson - Mkyong.com
May 2, 2024 - package com.mkyong.json.gson; import com.google.gson.Gson; import com.mkyong.json.model.Person; public class GsonParseJsonStringExample { public static void main(String[] args) { String json = "{\"name\": \"mkyong\", \"age\": 20}"; Gson gson = new Gson(); Person person = gson.fromJson(json, Person.class); System.out.println(person); } } JSON Array.
Find elsewhere
🌐
Crunchify
crunchify.com › json tutorials › how to use gson -> fromjson() to convert the specified json into an object of the specified class
How to use Gson -> fromJson() to convert the specified JSON into an Object of the Specified Class • Crunchify
February 16, 2023 - package crunchify.com.tutorials; ... /** * @author Crunchify.com * Gson() -> fromJson() to deserializes the specified Json into an object of the specified class */ public class CrunchifyGoogleGSONExample { public static void ...
🌐
ZetCode
zetcode.com › java › gson
Java Gson - JSON serialization and deserialization in Java with Gson
October 10, 2024 - import com.google.gson.Gson; void main() { String json_string = """ {"firstName":"Tom", "lastName": "Broody"}"""; Gson gson = new Gson(); User user = gson.fromJson(json_string, User.class); System.out.println(user); } record User(String firstName, String lastName) { }
🌐
HowToDoInJava
howtodoinjava.com › home › gson › gson jsonparser
Gson JsonParser (with Examples) - HowToDoInJava
April 4, 2023 - String json = "{'id': 1001, " + "'firstName': 'Lokesh'," + "'lastName': 'Gupta'," + "'email': 'howtodoinjava@gmail.com'}"; JsonObject jsonObject = new Gson().fromJson(json, JsonObject.class); System.out.println(jsonObject.get("id")); ...
🌐
GitHub
github.com › google › gson › issues › 2244
Strings with characters " and \ causing issues when parsing to class using fromJSON · Issue #2244 · google/gson
November 25, 2022 - When using fromJSON to parse JSON into a class with a String member and the source JSON string contains " or \, then GSON will either produce wrong string or throw an exception.
Author   pjoe
🌐
HowToDoInJava
howtodoinjava.com › home › gson › gson tutorial: read and write json with examples
Gson Tutorial: Read and Write JSON with Examples
August 27, 2023 - Getting Started Guide – Learn to use GSON to serialize a simple Java Object into the JSON representation and to deserialize the JSON string to an equivalent Java object.
🌐
Coderanch
coderanch.com › t › 631611 › open-source › GSON-deserialize-JSON-String
Using GSON to deserialize a JSON String (Open Source Projects forum at Coderanch)
There's a LOT of stuff in that post, which leads me to suspect that you're flapping around for a solution. I'm no GSON or JSON expert, but the first thing I would do is to break the problem down. And the first thing is, does: DietSchedule schedule = gson.fromJson(jsonContents, DietSchedule.class); return you anything?
🌐
Java67
java67.com › 2017 › 05 › how-to-convert-json-string-to-java-object-gson-example.html
How to convert JSON String to Java Object using Gson? JSON Deserialization Example | Java67
You can use any JSON library to perform serialization and de-serialization like Jackson Databind, Gson, or Json-simple. In this program, I'll show you how to use Gson to create a Java object from a given JSON String. In order to start with, we need a JSON String.
🌐
HowToDoInJava
howtodoinjava.com › home › gson › gson – read and write json
Gson - Read and Write JSON - HowToDoInJava
April 4, 2023 - Deserialization in the context of Gson means converting a JSON string to an equivalent Java object. To do the deserialization, we need a Gson object and call the function fromJson() and pass two parameters i.e. JSON string and expected java ...
🌐
Adobe Developer
developer.adobe.com › experience-manager › reference-materials › 6-4 › javadoc › com › google › gson › Gson.html
Gson ("The Adobe AEM Quickstart and Web Application.")
This method deserializes the Json ... type. For non-generic objects, use fromJson(Reader, Class) instead. If you have the Json in a String form instead of a Reader, use fromJson(String, Type) instead....
🌐
Stack Overflow
stackoverflow.com › questions › 55971802 › how-does-gson-fromjsonstring-class-work
java - How does Gson.fromJson(String, Class) work? - Stack Overflow
import com.google.gson.annotations.SerializedName data class UsuariosDTO ( @SerializedName("data") var data: List<Usuarios> ) data class Usuarios( @SerializedName("uid") var uid: String, @SerializedName("name") var name: String, @SerializedName("email") var email: String, @SerializedName("profile_pic") var profilePic: String, @SerializedName("post") var post: Post ) data class Post( @SerializedName("id") var id: Int, @SerializedName("date") var date: String, @SerializedName("pics") var pics: List<String> ) I'm able to use (where dataObteined is of UsuariosDTO type): val json = gson.toJson(dataObtained) And later deserialize the json like this: val offUsuariosDTO = gson.fromJson(json, UsuariosDTO::class.java) After looking everywhere I found out my error was UsuariosDTO.class.