Caleb Huggins Caleb Huggins - 11 months ago 48
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

Answer Source

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

public class Command{

  private String cmd;

  private String params;

  private String output;

 // Getters and setters


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.