Skip to content

Instantly share code, notes, and snippets.

@leoleozhu
Created July 10, 2013 08:39
Show Gist options
  • Save leoleozhu/5964515 to your computer and use it in GitHub Desktop.
Save leoleozhu/5964515 to your computer and use it in GitHub Desktop.
Use gson to parse integer array
package com.foo;
import java.util.Arrays;
import java.util.List;
import com.google.gson.Gson;
public class Foo {
private static List<Integer> toList(String json, Gson parser) {
return parser.fromJson(json, List.class);
}
private static int[] toArray(String json, Gson parser) {
return parser.fromJson(json, int[].class);
}
public static void main(String[] args) {
String json = new String("[1, 2, 3, 4]");
Gson parser = new Gson();
int[] arr = toArray(json, parser);
System.out.println(Arrays.toString(arr)); // prints [1, 2, 3, 4]
List<Integer> list = toList(json, parser);// prints [1.0, 2.0, 3.0, 4.0], not integer values
System.out.println(list.toString());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment