1

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

Wiggle
  • 23
  • 4

2 Answers2

1

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;
    }
}
Charlie
  • 2,876
  • 19
  • 26
1

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();
}
Crispert
  • 1,102
  • 7
  • 13
  • I would have done this from the beginning, but it depends on the location of your file. If `test.json` is in the `raw` resource folder you can use `new InputStreamReader(getResources().openRawResource(R.raw.test))` (the extension is ignored). If it's on the sd card, the answer is a bit longer. – Crispert Feb 17 '18 at 20:22
  • thank you very much! its working! one more question - what is the difference between putting .json file is assets folder or raw ? – Wiggle Feb 17 '18 at 20:29
  • Here is an explanation https://stackoverflow.com/questions/9563373/the-reason-for-assets-and-raw-resources-in-android – Crispert Feb 17 '18 at 20:33
  • tyvm again! can i give you +karma ? :D – Wiggle Feb 17 '18 at 20:35