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?
asked Mar 1, 2013 at 13:22
Fabian
3561 gold badge5 silver badges15 bronze badges
-
look at the JSONArray and JSONObject classesx4rf41– x4rf412013年03月01日 13:23:22 +00:00Commented Mar 1, 2013 at 13:23
-
what about GSON? javacodegeeks.com/2011/01/…fmsf– fmsf2013年03月01日 13:31:46 +00:00Commented Mar 1, 2013 at 13:31
2 Answers 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);
answered Mar 1, 2013 at 13:42
vikasing
11.8k3 gold badges27 silver badges25 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Fabian
Okay, and if I have an arraylist of games. Can I just put the arraylist into the toJSON function of the gson object?
vikasing
yes, have a look at sites.google.com/site/gson/…
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;
}
}
answered Mar 1, 2013 at 13:43
Cameron Lowell Palmer
22.4k7 gold badges131 silver badges135 bronze badges
2 Comments
Fabian
Does GSON also work with arraylists of objects? In the examples I only see primitive types or objects.
Cameron Lowell Palmer
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.
lang-java