【问题标题】:create a JSON Array of objects in java android在java android中创建一个JSON对象数组
【发布时间】:2013-03-01 13:22:14
【问题描述】:

我创建了一个类 Game,如下所示:

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 或更多。

我的问题是,如何创建游戏对象的 JSON 数组?

【问题讨论】:

标签: java android json arraylist


【解决方案1】:

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

【讨论】:

  • 好的,如果我有一个游戏数组列表。可以直接把arraylist放到gson对象的toJSON函数中吗?
【解决方案2】:

最好的办法是进入 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;
    }
}

【讨论】:

  • GSON 是否也适用于对象的数组列表?在示例中,我只看到原始类型或对象。
  • 是的。确实如此。我将它用于非常复杂的对象序列化和反序列化。有趣的个人经历,出站(JAVA-to-JSON)序列化执行比入站(JSON-to-JAVA)序列化慢。
猜你喜欢
  • 2014-06-03
  • 2013-07-22
  • 2021-12-24
  • 2021-09-22
  • 1970-01-01
  • 2021-03-16
  • 2013-06-04
  • 2017-02-23
  • 1970-01-01
相关资源
最近更新 更多