簡體   English   中英

在 Groovy 中生成 JSON object

[英]Generate JSON object in Groovy

由於某種原因,我無法使用 JSONBuilder 在 Groovy 中創建 JSON object

這是我所擁有的,但它又回來了{}:

import groovy.json.JsonBuilder

JsonBuilder builder = new JsonBuilder()
    builder {
        name "Name"
        description "Description"
        type "schedule type"
        schedule {
          recurrenceType "one time"
          start "${startDateTime}"
          end "${endDateTime}"
        }
        scope {
          entities ["${applicationId}"]
          matches [
            {
              tags [
                {
                  key "key name"
                  context "some context"
                }
              ]
            }
          ]
        }
      }

有誰知道用嵌套元素創建 JSON object 的簡單方法?

  1. 如果您要從 Groovy 對象創建 JSON,那么您可以使用; json輸出

  2. 如果你有幾個值要傳遞並創建一個 JSON object,那么你可以使用; JsonGenerator

  3. 或者您可以使用 JsonBuilder 或 StreamingJsonBuilder

檢查groovy 文檔

我傾向於發現JsonOutput更易於用於已構建的數據。 你的看起來像這樣:

groovy.json.JsonOutput.toJson(
   [name: "Name",
    description: "Description",
    type: "schedule type",
    schedule: [
        recurrenceType: "one time",
        start: "${startDateTime}",
        end: "${endDateTime}"
    ],
    scope: [
        entities: ["${applicationId}"],
        matches: [
            [
                tags: [
                    [
                        key: "key name",
                        context: "some context"
                    ]
                ]
            ]
        ]
    ]]
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM