Caleb Huggins Caleb Huggins - 3 months ago 9
JSON Question

Parse indefinite ammount of variables from JSON

I am currently trying to load an indefinite amount of variables from a JSON array, and have no idea how to do this. My JSON file is as follows:

{"commands": [
{"cmd": "hello", "params": "%u", "output": "hello %s!"},
{"cmd": "ping", "params": "", "output": "pong!"},
{"cmd": "test", "params": "%ul", "output": "test %s.."}
]}


I am using the GSON library from Google. Would I have to manually parse each command, or is there a way to achieve this with
gson.fromJson()
?

Answer

You can use a wrapper object containing an array or a collection of Command objects as a model for the deserialization process:

Command.java

public class Command{

  private String cmd;

  private String params;

  private String output;

 // Getters and setters

}

CommandWrapper.java

public class CommandWrapper{

  private List<Command> commands;

  // Getters and setters

}

And then in your class you can deserialize the JSON this way:

 Gson gson = new Gson();
 CommandWrapper wrapper = gson.fromJson(myInputJson, CommandWrapper.class);

And get your commands as a list.