Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Gson, how do I add a JsonArray to a JsonObject?

Tags:

java

json

gson

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  
  ]
}

Some questions about building this Json:

  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.

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?

EDIT: 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).

like image 621
Cache Staheli Avatar asked Jul 28 '16 17:07

Cache Staheli


People also ask

How can we create correct JSONArray in Java using JSON object?

jsonObject. put("key", "value"); Create a JSON array by instantiating the JSONArray class and add, elements to the created array using the add() method of the JSONArray class.

What is the difference between JSONArray and JSON object?

JSONObject and JSONArray are the two common classes usually available in most of the JSON processing libraries. A JSONObject stores unordered key-value pairs, much like a Java Map implementation. A JSONArray, on the other hand, is an ordered sequence of values much like a List or a Vector in Java.

How do I add a list to a JSON object in Java?

JSONObject obj = new JSONObject(); List<String> sList = new ArrayList<String>(); sList. add("val1"); sList. add("val2"); obj. put("list", sList);

How do you initiate JSONArray?

1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.

How add JSON array to another JSON array?

We can merge two JSON arrays using the addAll() method (inherited from interface java. util.

How do I get items from JSONArray?

JSONArray jsonArray = (JSONArray) jsonObject. get("contact"); The iterator() method of the JSONArray class returns an Iterator object using which you can iterate the contents of the current array.


1 Answers

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

like image 154
thewmo Avatar answered Oct 18 '22 08:10

thewmo