i am fairly new to GSON and get a JSON response of this format (just an easier example, so the values make no sense):
{
"Thomas": {
"age": 32,
"surname": "Scott"
},
"Andy": {
"age": 25,
"surname": "Miller"
}
}
I want GSON to make it a Map, PersonData is obviously an Object. The name string is the identifier for the PersonData.
As I said I am very new to GSON and only tried something like:
Gson gson = new Gson();
Map<String, PersonData> decoded = gson.fromJson(jsonString, new TypeToken<Map<String, PersonData>>(){}.getType());
but this threw the error:
Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was STRING at line 1 column 3141
Any help is appreciated :)
Serialization in the context of Gson means converting a Java object to its JSON representation. In order to do the serialization, we need to create the Gson object, which handles the conversion. Next, we need to call the function toJson() and pass the User object. Program output.
Overview. Gson is a Java library that can be used to convert Java Objects into their JSON representation. It can also be used to convert a JSON string to an equivalent Java object.
As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.
The following works for me
static class PersonData {
int age;
String surname;
public String toString() {
return "[age = " + age + ", surname = " + surname + "]";
}
}
public static void main(String[] args) {
String json = "{\"Thomas\": {\"age\": 32,\"surname\": \"Scott\"},\"Andy\": {\"age\": 25,\"surname\": \"Miller\"}}";
System.out.println(json);
Gson gson = new Gson();
Map<String, PersonData> decoded = gson.fromJson(json, new TypeToken<Map<String, PersonData>>(){}.getType());
System.out.println(decoded);
}
and prints
{"Thomas": {"age": 32,"surname": "Scott"},"Andy": {"age": 25,"surname": "Miller"}}
{Thomas=[age = 32, surname = Scott], Andy=[age = 25, surname = Miller]}
So maybe your PersonData
class is very different.
You can use gson.toJsonTree(Object o)
to convert your custom object to JSON format.
The following works for me:
private static class PersonData {
private int age;
private String surname;
public PersonData(int age, String surname) {
this.age = age;
this.surname = surname;
}
}
public static void main(String[] args) {
PersonData first = new PersonData(24, "Yovkov");
PersonData second = new PersonData(25, "Vitanov");
Gson gson = new Gson();
JsonObject jsonObject = new JsonObject();
jsonObject.add("kocko", gson.toJsonTree(first));
jsonObject.add("deyan", gson.toJsonTree(second));
System.out.println(gson.toJson(jsonObject));
}
and prints:
{"kocko":{"age":24,"surname":"Yovkov"},"deyan":{"age":25,"surname":"Vitanov"}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With