2013-03-01 37 views
1

我創建了一個類遊戲,看起來像這樣的Java對象的JSON數組:創建的Android

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 

而且我有一個ArrayList的,看起來像這樣:

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

此ArrayList包含5場比賽。我想把這些遊戲發送到一個php腳本中,所以我認爲最聰明的方法是創建一個JSON數組對象並將它們發送給php腳本,因爲這些遊戲在某些時候也可能會達到100個或更多。

我的問題是,我如何創建一個Game對象的JSON數組?

+0

看看JSONArray和JSONObject類 – x4rf41 2013-03-01 13:23:22

+0

GSON呢? http://www.javacodegeeks.com/2011/01/android-json-parsing-gson-tutorial.html – fmsf 2013-03-01 13:31:46

回答

1

的最好的事情就是進入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; 
    } 
} 
+0

GSON是否也與對象的數組列表一起工作?在示例中,我只看到原始類型或對象。 – Fabian 2013-03-01 13:46:51

+0

是的。它的確如此。我將它用於非常複雜的對象序列化和反序列化。有趣的個人經驗,出站(JAVA到JSON)序列化比入站(JSON到JAVA)序列化執行速度慢。 – 2013-03-02 11:31:56

2

使用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); 
+0

好的,如果我有遊戲陣列。我可以將數組列表放入gson對象的toJSON函數嗎? – Fabian 2013-03-01 13:44:23

+0

是的,看看https://sites.google.com/site/gson/gson-user-guide#TOC-Serializing-and-Deserializing-Collection-with-Objects-of-Arbitrary-Types – vikasing 2013-03-01 13:48:02