user836200
user836200

Reputation: 655

Android json/gson deserialization

I am trying to parse the following json array that I receive from my php file:

actionsArray = [["19.431","19.438"],[["8","107"],[]],["u1","u2"]]

I'm primarily interested in accessing the array [["8","107"],[]]; however, I get the error, "com.google.gson.JsonParseException: Expecting array but found object: Name: null Grams: null 0 Actions: null

Here's an excerpt from my code:

User class contains: String name; int[] actions; String grams

            JSONArray inputarray;
            try {
                int[] userActionsArray = new int[0];
                inputarray = new JSONArray(br.readLine());

                JSONArray gramsArray = (JSONArray)inputarray.get(0);
                JSONArray actionsArray = (JSONArray)inputarray.get(1);
                JSONArray namesArray = (JSONArray) inputarray.get(2);

                User[] values = new User[namesArray.length()];

                Gson gson = new Gson();
                *User userAction = gson.fromJson(inputarray.toString(), User.class); 
                //error occurs on the above line*
                ...

Upvotes: 0

Views: 804

Answers (2)

Satish Rajput
Satish Rajput

Reputation: 21

This problem occurs usually when you try to parse array but service is responding as object. So first test the response you are getting then try to parse accordingly.

Upvotes: 2

Salil Pandit
Salil Pandit

Reputation: 1498

A JSONArray is from org.json, which the .toString() method returns as ["first","second"] (source available here)

You need your JSON to look like: { myArray : [ "first", "second" ] } for Gson to parse it... Where your POJO (in your case User.class) should look like this:

public User {
 String[] myArray;
}

Upvotes: 1

Related Questions