使用gson解析JSON对象

onC*_*ate 7 android json gson

我正在尝试解析JSON,如:

{"response":[123123, 1231231, 123124, 124124, 111111, 12314]}
Run Code Online (Sandbox Code Playgroud)

有了GSON,制作

Gson gson = new GsonBuilder().create();
int[] friends = new Gson().fromJson(answer, int[].class);
System.out.print(friends[0]);
Run Code Online (Sandbox Code Playgroud)

但是得到 Error Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

如何在数组中解析这些数字?

Jos*_*man 10

您将首先想要创建一个模型类,GSON可以将您的json绑定到:

public class ResponseModel {

    private List<Integer> response = new ArrayList<Integer>();

    public List<Integer> getResponse() {
        return response;
    }

    @Override
    public String toString() {
        return "ResponseModel [response=" + response + "]";
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以打电话

Gson gson = new Gson();
ResponseModel responseModel = gson.fromJson("{\"response\":[123123, 1231231, 123124, 124124, 111111, 12314]}",
                                            ResponseModel.class);
List <Integer> responses = responseModel.getResponse();
// ... do something with the int list
Run Code Online (Sandbox Code Playgroud)


Bri*_*ach 7

除了使用包装类之外,另一个选项就是从解析树中获取数组.

使用JsonParser创建树,从中获取数组,然后转换为int[]使用Gson:

public class App 
{
    public static void main( String[] args ) throws IOException
    {
       String json = "{\"response\":[1,2,3,4,5]}";

       JsonObject jo = new JsonParser().parse(json).getAsJsonObject();
       JsonArray jsonArray = jo.getAsJsonArray("response");

       int[] myArray = new Gson().fromJson(jsonArray, int[].class);

       System.out.println(Arrays.toString(myArray));

    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,您也可以JsonArray直接int[]使用它,而不是根据您的使用情况将其转换为.

System.out.println(jsonArray.get(0).getAsInt());
Run Code Online (Sandbox Code Playgroud)