在Gson中,如何将JsonArray添加到JsonObject? [英] In Gson, how do I add a JsonArray to a JsonObject?

查看:355
本文介绍了在Gson中,如何将JsonArray添加到JsonObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在尝试获得这样的Json结构:

Suppose that I am trying to get a Json structure like this:

{
  "rows": [
    {
      "date_str": "2016-07-01",
      "sleep_7_or_more_hours": true,
      "activity_minutes": "0",
      "water_5_or_more_cups": true,
      "fruit_veg_4_or_more_servings": true,
      "physical_activity_description": "walking"
    }
    {
      "date_str": "2016-07-02",
      "sleep_7_or_more_hours": true,
      "activity_minutes": "30",
      "water_5_or_more_cups": true,
      "fruit_veg_4_or_more_servings": true,
      "physical_activity_description": "walking"
    }  
    ...etc  
  ]
}

有关构建此Json的一些问题:

Some questions about building this Json:

  1. 如何指定JsonArray的名称?我需要在Json中将其命名为"rows".
  2. 如何将JsonArray rows添加到JsonObject(我想这就是外括号的意思)?
  1. How can I specify the name of the JsonArray? I need it to be named, in the Json, "rows".
  2. How can I add the JsonArray rows to a JsonObject (I assume that's what the outer brackets mean)?

这是我正在使用的代码:

This is the code that I am using to do it:

JsonArray rows = new JsonArray();

//Code to get local dates omitted
for (LocalDate date = start; !date.isAfter(end); date = date.plusDays(1))
{
    JsonObject row = new JsonObject();

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd", Locale.ENGLISH);
    String dateString = date.format(formatter);
    row.addProperty("date_str", dateString);

    boolean sleptLongEnough = (sleepLog.getTimeInBed(getDate(date)) > (7 * 60));
    row.addProperty("sleep_7_or_more_hours", sleptLongEnough);

    int activityMinutes = (activitiesLog.getMinutesVeryActive(getDate(date)) + activitiesLog.getMinutesFairlyActive(getDate(date)));
    ...
    //Omitted extra code
    rows.add(row);
}
JsonObject logs = new JsonObject();
//add rows to logs here.

我需要将rows添加到logs.但是,JsonObject似乎仅具有.add(JsonElement).addProperty(String, variousTypes),并且没有添加数组的内容.我想念什么?

I need to add rows to logs. However, JsonObject only appears to have .add(JsonElement) and .addProperty(String, variousTypes), and nothing to add an array. What am I missing?

编辑:我不使用Gson来序列化对象,因为Json由来自多个日志中的每个日志的数据项组成(甚至不接近每个日志中的所有信息).

I am not using Gson to serialize objects because the Json is composed of data items from each of several logs (and not even close to all of the information in each log).

推荐答案

JsonArrayJsonElement的实例.因此.add("name", element)方法(其中element是JsonArray)应该可以工作.

JsonArray is an instance of JsonElement. So the method .add("name", element), where element is a JsonArray, should just work.

这篇关于在Gson中,如何将JsonArray添加到JsonObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆