Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a typed ArrayList from a JSON String in Java

Tags:

java

json

I convert an ArrayList into an JSON String and save it into a File. This works perfectly. But if I try do this in reverse, my application doesn't run (I get something like a ClassCastException)

Can somebody tell me what's wrong with my code?

BufferedReader br = new BufferedReader(
new FileReader("/sdcard/file.json"));

myArrayList = gson.fromJson(br, ArrayList.class);
like image 427
faabi Avatar asked Jun 07 '26 22:06

faabi


1 Answers

Here's a SSCCE that executes and that demonstrates exactly how to get back a typed ArrayList:

public static void main(String args[]) {
    Gson gson = new Gson();

    List<Integer> outList = new ArrayList<Integer>();
    outList.add(1);
    outList.add(2);
    outList.add(3);

    String json = gson.toJson(outList);

    // This is how you tell gson about the generic type you want to get back:
    Type type = new TypeToken<ArrayList<Integer>>(){}.getType();
    ArrayList<Integer> inList = gson.fromJson(json, type);

    for (int i : inList) {
        System.out.println(i);
    }
}

Output:

1
2
3

The fact that this code doesn't explode proves that the ArrayList is in fact typed correctly.

I went to/from String not via a file to simplify the example down to the bare minimum.

like image 110
Bohemian Avatar answered Jun 10 '26 18:06

Bohemian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!