1

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?

2
  • look at the JSONArray and JSONObject classes Commented Mar 1, 2013 at 13:23
  • what about GSON? javacodegeeks.com/2011/01/… Commented Mar 1, 2013 at 13:31

2 Answers 2

2

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

Okay, and if I have an arraylist of games. Can I just put the arraylist into the toJSON function of the gson object?
yes, have a look at sites.google.com/site/gson/…
1

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;
    }
}

2 Comments

Does GSON also work with arraylists of objects? In the examples I only see primitive types or objects.
Yes. It does. I use it for very complex object serialization and deserialization. Interesting personal experience, outbound (JAVA-to-JSON) serialization performed slower than inbound (JSON-to-JAVA) serialization.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.