Wiggle
Wiggle

Reputation: 23

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column

im learning parcing and got a problem trying to make it happen. found a lot of similar questions and more solutions but nothing helped me

thats my json

{
  "firstName": "name",
  "lastName": "last",
  "resistances": {
    "a1": 1,
    "a2": 2,
    "a3": 3,
    "a4": 4
  }
}

Player.class

class Player implements Serializable{

    String firstName;
    String lastName;
    int[] resistances;

    public Player(String firstName, String lastName, int[] resistances) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.resistances = resistances;
    }
}

and how i try to parce

Gson gson = new Gson();
Player player = gson.fromJson("test.json", Player.class);

SOS

Upvotes: 1

Views: 787

Answers (2)

Crispert
Crispert

Reputation: 1167

fromJson(String, Class) parses the String itself, in your case test.json, not the file it represents. You need to create a Reader from the file you are trying to parse and pass it as first argument.

If test.json is in the external storage:

String fpath = Environment.getExternalStorageDirectory() + "/path/to/test.json";
 try {
        FileReader fr = new FileReader(fpath));
        gson.fromJson(fr, Player.class);
} catch (Exception e1) {
        e1.printStackTrace();
}

Upvotes: 1

Charlie
Charlie

Reputation: 3094

Your JSON "resistances" object should look like this for your parsing code to work:

{
  "firstName": "name",
  "lastName": "last",
  "resistances": [
    1, 2, 3, 4
  ]
}

Or, change the resistances variable in Java to a Map. Look here for a previous answer - GSON can parse a dictionary JSON object to a Map.

class Player implements Serializable {

    String firstName;
    String lastName;
    Map<String, Integer> resistances;

    public Player(String firstName, String lastName, Map<String, Integer> resistances) {
        this.firstName   = firstName;
        this.lastName    = lastName;
        this.resistances = resistances;
    }
}

Upvotes: 1

Related Questions