Gson gson = new Gson();
gson.fromJson(jsonStr,YourClass.class);
very easy.
Answer from David Wang on Stack OverflowGson 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);
Videos
First of all: there are no "gson" objects. There is just JSON data, strings in a specific format, and the Gson tooling allows you to turn JSON strings into java objects (json parsing), and turning java objects into JSON strings. Coming from there, your request boils down to:
Gson gson = new Gson();
String json = gson.toJson(someInstanceOfStaff);
Beyond that, you should acquire a good tutorial and study this topic, like this one here.
Examples from the API:
Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target = new MyType();
String json = gson.toJson(target); // serializes target to Json
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2
For lists or parameterized types:
Type listType = new TypeToken<List<String>>() {}.getType();
List<String> target = new LinkedList<String>();
target.add("blah");
Gson gson = new Gson();
String json = gson.toJson(target, listType);
List<String> target2 = gson.fromJson(json, listType);
API docs and link for more examples