How to deserialize an array of unknown dimension using Gson?
I tried to use
.fromJson(mystring, Object.class);
but got nested ArrayList-s.
I want to get nested double[][]...[]
Is it possible?
UPDATE
I wrote the following custom adapter
public class DoubleArrayAdapter extends TypeAdapter<Object> {
@Override
public void write(JsonWriter out, Object value) throws IOException {
if( value.getClass().isArray() ) {
out.beginArray();
int length = Array.getLength(value);
for (int i = 0; i < length; i ++) {
Object arrayElement = Array.get(value, i);
write(out, arrayElement);
}
out.endArray();
}
else {
out.value((double) value);
}
}
@Override
public Object read(JsonReader in) throws IOException {
if( in.peek() == JsonToken.BEGIN_ARRAY ) {
ArrayList<Object> elements = new ArrayList<>();
in.beginArray();
do {
elements.add(read(in));
} while( in.peek() != JsonToken.END_ARRAY );
in.endArray();
if( elements.size() == 0 ) {
return new double[0];
}
else {
Class cls = elements.get(0).getClass();
if( cls.isArray() ) {
Object ans = Array.newInstance(cls, elements.size());
for(int i=0; i<elements.size(); ++i) {
Array.set(ans, i, elements.get(i));
}
return ans;
}
else {
double[] ans = new double[elements.size()];
for(int i=0; i<elements.size(); ++i) {
ans[i] = (double) elements.get(i);
}
return ans;
}
}
}
else {
return in.nextDouble();
}
}
}
and prepare a Gson object with the following code
public static Gson getGsonWithDoubleArrayAdapter() {
if( gson == null ) {
gson = new GsonBuilder()
.serializeNulls()
.setPrettyPrinting()
.registerTypeAdapter(Object.class, new DoubleArrayAdapter())
.create();
}
return gson;
}
But it looks like it still doesn't activate (still generates ArrayList-s).
+3
source to share
2 answers
I would use lists instead, since they don't have a given length:
Gson gson = new Gson();
ClassName download = gson.fromJson(input, ClassName.class); // creates POJO from input, into a ClassName object
Thus, which ClassName
reminds:
public class ClassName {
String name;
List<ObjInList> list;
}
public class ObjInList {
String description;
float price;
}
I also recommend this website for this process (no affiliation)
0
source to share
First I found the error in my adapter, it should be
if( in.peek() == JsonToken.BEGIN_ARRAY ) {
ArrayList<Object> elements = new ArrayList<>();
in.beginArray();
do {
elements.add(read(in));
} while( in.peek() != JsonToken.END_ARRAY );
in.endArray();
ans also later
if( cls.isArray() ) {
Object ans = Array.newInstance(cls, elements.size());
for(int i=0; i<elements.size(); ++i) {
Array.set(ans, i, elements.get(i));
}
return ans;
}
etc.
And then I parsed the line with this adapter directly, with the code
new DoubleArrayAdapter().fromJson(new StringReader(mystring));
0
source to share