Creating array list of java objects from JSON URL with Gson
17,482
You could specify the type to deserialize into as an array or as a collection.
As Array:
import java.io.FileReader;
import com.google.gson.Gson;
public class GsonFoo
{
public static void main(String[] args) throws Exception
{
Data0[] data = new Gson().fromJson(new FileReader("input.json"), Data0[].class);
System.out.println(new Gson().toJson(data));
}
}
class Data0
{
String name;
String address;
String type;
String notes;
}
As List:
import java.io.FileReader;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class GsonFoo
{
public static void main(String[] args) throws Exception
{
List<Data0> data = new Gson().fromJson(new FileReader("input.json"), new TypeToken<List<Data0>>(){}.getType());
System.out.println(new Gson().toJson(data));
}
}
Comments
-
NullPointer almost 2 years
I am able to parse the following data into a java object:
{ "name": "testname", "address": "1337 455 ftw", "type": "sometype", "notes": "cheers mate" }
using this code:
public class Test { public static void main (String[] args) throws Exception { URL objectGet = new URL("http://10.0.0.4/file.json"); URLConnection yc = objectGet.openConnection(); BufferedReader in = new BufferedReader( new InputStreamReader( yc.getInputStream())); Gson gson = new Gson(); try { DataO data = new Gson().fromJson(in, DataO.class); System.out.println(data.getName()); }catch (Exception e) { e.printStackTrace(); } } }
But now I want to store a list of these objects out of the following JSON String:
[ { "name": "testname", "address": "1337 455 ftw", "type": "sometype", "notes": "cheers mate" }, { "name": "SumYumStuff", "address": "no need", "type": "clunkdroid", "notes": "Very inefficient but high specs so no problem." } ]
Could someone help me modify my code to do this?