Fabian
Fabian

Reputation: 356

create a JSON Array of objects in java android

I have created a class Game that looks like this:

public class Game{
private String name;
private String location;
private int participants;

public Game(String name, String location, int participants){
     this.name = name;
     this.location = location;
     this. participants = participatns;
}

//getters and setters of all properties

And I have a ArrayList that looks like this:

 ArrayList<Game>gameList = new ArrayList<Game>();

This ArrayList contains 5 games. I want to send those games to a php script so I figured that the smartest way to do this is to create a JSON array of objects and send those to the php script because those games could also be a 100 or more at some point.

My question is, how do I create a JSON array of Game objects?

Upvotes: 1

Views: 250

Answers (2)

Cameron Lowell Palmer
Cameron Lowell Palmer

Reputation: 22246

The best thing to do is get into GSON. GSON web site,

public class ExampleObject {
    public static final String API_KEY = "get_response";
    private static final String OFFSETS = "offsets";

    @SerializedName(OFFSETS)
    private List<Integer> mOffsets;



    public ExampleObject() {
        super();
    }

    public String getAPIKey() {
        return API_KEY;
    }

    public List<Integer> getOffsets() {
        return mOffsets;
    }
}

Upvotes: 1

vikasing
vikasing

Reputation: 11772

Use Gson: https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson

Game game = new Game();
Gson gson = new Gson();
String json = gson.toJson(game); 

Upvotes: 2

Related Questions