I have a class with two fields.
public class Example {
private String exampleString;
private List<Example2> example2List;
public Example(String exampleString, List<Example2> example2List) {
this.exampleString = exampleString;
this.example2List = example2List;
}
public String getString() {
return exampleString;
}
public List<Example2> getExample2List() {
return example2List;
}
}
In another class I want to convert my Example.class to a JSON String with GSON and convert it back.
public class MainExample {
public MainExample() {
Gson mGson = new Gson();
List<Example2> example2List = new ArrayList<>();
example2List.add(new Example2());
example2List.add(new Example2());
Example example1 = new Example("hello", example2List);
String resultToJSON = mGson.toJson(example1); //This works fine. The example2List is stored as a JSON Array.
Example resultFromJSON = mGson.fromJson(resultToJSON, Example.class); // This gives me an error: "Expected BEGIN_OBJECT but was NUMBER at line 1 column 2 path $"
}
}
I found some solutions on how to deal with JSON Arrays in GSON but I did not find any on how to deal with fields which are lists from an object which should be converted to JSON via Gson.
Any solutions to this? Thanks in advance!
EDITS:
public class Example2 {
private String string;
private int integer;
public Example2(String string, int integer) {
this.string = string;
this.integer = integer;
}
public String getString() {
return string;
}
public int getInt() {
return integer;
}
}