I don’t know libraries that supports mapping between JSON Arrays (“data” is an array of arrays) and Java object fields.
The gson library let you map your JSON Array into an array of array of java String, but then you have to convert it to your object model.
You can parse your JSON into this object:
class DataWrapper
{
String[] columns;
String[][] data;
}
Another solution is to use the JSonReader and stream out your objects using this class:
import java.io.IOException;
import java.io.Reader;
import java.util.Iterator;
import com.google.gson.stream.JsonReader;
public class TransportJSonReader implements Iterator<Transport> {
protected JsonReader jsonReader;
public TransportJSonReader(Reader reader) throws IOException
{
jsonReader = new JsonReader(reader);
jsonReader.beginObject();
//columns
jsonReader.nextName();
jsonReader.skipValue();
//data
jsonReader.nextName();
jsonReader.beginArray();
}
@Override
public boolean hasNext() {
try {
return jsonReader.hasNext();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public Transport next() {
if (!hasNext()) throw new IllegalStateException();
try {
jsonReader.beginArray();
String name = jsonReader.nextString();
String description = jsonReader.nextString();
String id = jsonReader.nextString();
jsonReader.endArray();
return new Transport(id, name, description);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}
It is an iterator so you can use it in this way:
TransportJSonReader reader = new TransportJSonReader(new StringReader(json));
while(reader.hasNext()) System.out.println(reader.next());
1
solved Json to java objects mapping [closed]