【问题标题】:Gson, creating a simple JsonArray of JsonObjectsGson,创建一个简单的 JsonObjects 的 JsonArray
【发布时间】:2016-08-06 15:48:42
【问题描述】:

我正在尝试使用 gson 构建 JsonObjects 的 JsonArray。 每个 JsonObject 都会采用以下格式,

{"image":"name1"}
{"image":"name2"}

等等。

我有一个名称的字符串数组 ("name1","name2",...) 我无法将字符串数组直接转换为 JsonArray。我正在尝试迭代地创建 JsonObjects 并将其添加到 JsonArray。

        JsonObject innerObject;
        JsonArray jArray = new JsonArray();
        for(int i = 0; i<names.length; i++)
        {
            innerObject = new JsonObject();
            innerObject.addProperty("image",names[i]);
            jArray.add(innerObject);
        } 

但据我了解,JsonArray 中的add 方法需要一个 JsonElement,而这里我给出的是一个 JsonObject。我找不到将 JsonObject 转换为 JsonElement 的方法。 当我这样做时,使用 gson 的全部意义就消失了。有没有更好的办法?

【问题讨论】:

  • JsonObject 扩展JsonElement,因此没有理由不能使用add(JsonElement) 方法向JsonArray 添加一个。无需转换。
  • 感谢您的帮助

标签: java json gson


【解决方案1】:

首先,创建一个代表单个 json 对象的类,例如:

class MyObject {
    private String image;

    public MyObject(String name) { image = name; }
}

Gson 将使用类的变量名称来确定要使用的属性名称。

然后使用您可用的数据创建一个数组或列表,例如

ArrayList<MyObject> allItems = new ArrayList<>();
allItems.add(new MyObject("name1"));
allItems.add(new MyObject("name2"));
allItems.add(new MyObject("name3"));

最后,要序列化为 Json,请执行以下操作:

String json = new Gson().toJson(allItems);

并将数据从json 取回到一个数组:

MyObject[] items = new Gson().fromJson(json, MyObject[].class);

对于简单的(反)序列化,不需要直接处理 Json 类。

【讨论】:

  • 感谢您的帮助!
  • 太棒了!您的示例代码对我帮助很大!谢谢。
【解决方案2】:

如果您要使用 GSON,请像这样使用它来转换为对象

List<Image>images = new Gson().fromJson(json, Image[].class);

获取json字符串

String json = new Gson().toJson(images);

这就是 gson 的重点,您不应该使用循环和其他东西来操作数据。您需要利用其强大的模型解析。

【讨论】:

    【解决方案3】:

    也许为时已晚,但是...如果您不需要它,有一种方法可以不用创建新类:

    import com.google.gson.JsonObject;
    import com.google.gson.JsonArray
    ...
    ...
    JsonArray jobj = new JsonArray();
    String[] names = new String[]{"name1","name2","name3"};
    for(String name : names) {
       JsonObject item = new JsonObject();
       item.addProperty("name",name);
       jobj.add(item);
    }
    System.out.println(jobj.toString());// ;)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多