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 OverflowHelp with using Gson to convert simple JSON string to Java object
java - Gson: Directly convert String to JsonObject (no POJO) - Stack Overflow
Strings with characters " and \ causing issues when parsing to class using fromJSON
JSON String to Java object using GSON - Stack Overflow
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();
To do it in a simpler way, consider below:
JsonObject jsonObject = (new JsonParser()).parse(json).getAsJsonObject();
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 OverflowI'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;
}
use JsonParser; for example:
CopyJsonObject o = JsonParser.parseString("{\"a\": \"A\"}").getAsJsonObject();
Try to use getAsJsonObject() instead of a straight cast used in the accepted answer:
CopyJsonObject o = new JsonParser().parse("{\"a\": \"A\"}").getAsJsonObject();
Gson gson = new Gson();
gson.fromJson(jsonStr,YourClass.class);
very easy.
The reason for the error is that your JSON at the top level is an array, not an object. That is covered by GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?.
However, the solution there won't work for your JSON because you have an array of mixed types (an object and an array) rather than an array of a single type of object. For that you're going to have to write a custom deserializer (See The section of the Gson user's guide that covers this) or use Gson's JsonParser class directly and extract the data from the parse tree.
Edit from comments above:
If you're the one creating the JSON, it looks like what you want is an array of BoxSearch objects?
Based on your Java BoxSearch class, you'd need JSON structured like:
[
{
"lat1" : 39.737567,
"lat2" : 32.7801399,
"long1" : -104.98471790000002,
"long2" : -96.80045109999998,
"boxes" : [
{
"lat": {
"b": 38.88368709500021,
"d": 40.620468491667026
},
"long": {
"b": -105.75306170749764,
"d": -104.675854661387
}
}
]
}
]
However, the way you have Boxes class defined won't work for that. (Did you mean to have an array of them?). As-is it would need to look like:
class Boxes {
Box lat;
@SerializedName("long")
Box lon;
}
class Box {
String b;
String d;
}
Now you have an array containing one type of object (BoxSearch) which you could deserialize with:
Type collectionType = new TypeToken<Collection<BoxSearch>>(){}.getType();
Collection<BoxSearch> boxSearchCollection = gson.fromJson(json, collectionType);
If you really don't need an array of these, get rid of the outer array and simply do:
gson.fromJson(json, BoxSearch.class);