├── .github └── workflows │ ├── build.yml │ └── release.yml ├── .gitignore ├── .travis.yml ├── CHANGES.md ├── LICENSE ├── README.md ├── build.gradle ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── publish-mavencentral.gradle ├── release_howto.md └── src ├── main └── kotlin │ └── com │ └── github │ └── holgerbrandl │ └── jsonbuilder │ └── JsonUtil.kt └── test └── kotlin ├── Examples.kt └── Tests.kt /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | # https://docs.github.com/en/free-pro-team@latest/actions/managing-workflow-runs/adding-a-workflow-status-badge 4 | 5 | on: 6 | push: 7 | branches: [ master ] 8 | pull_request: 9 | branches: [ master ] 10 | 11 | jobs: 12 | build: 13 | 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Set up JDK 11 19 | uses: actions/setup-java@v1 20 | with: 21 | java-version: 11 22 | - name: Grant execute permission for gradlew 23 | run: chmod +x gradlew 24 | - name: Build and test with gradle 25 | # https://stackoverflow.com/questions/50104666/gradle-difference-between-test-and-check 26 | # https://stackoverflow.com/questions/50104666/gradle-difference-between-test-and-check 27 | run: ./gradlew clean check --stacktrace --info -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | # Created with https://github.com/marketplace/actions/create-a-release 2 | 3 | on: 4 | push: 5 | # Sequence of patterns matched against refs/tags 6 | # branches: 7 | # - master 8 | tags: 9 | - 'v*' # Push events to matching v*, i.e. v1.0, v20.15.10 10 | 11 | name: Create Release 12 | 13 | 14 | jobs: 15 | build: 16 | name: Create Release 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Checkout code 20 | uses: actions/checkout@v2 21 | # https://github.community/t/accessing-commit-message-in-pull-request-event/17158/8 22 | # - name: get commit message 23 | # run: | 24 | # echo ::set-env name=commitmsg::$(git log --format=%B -n 1 ${{ github.event.after }}) 25 | # - name: show commit message 26 | # run: echo $commitmsg 27 | - name: Create Release 28 | id: create_release 29 | uses: actions/create-release@v1 30 | env: 31 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token 32 | with: 33 | # https://stackoverflow.com/questions/63619329/github-action-get-commit-message 34 | # tag_name: ${{ github.event.head_commit.message }} 35 | # release_name: ${{ github.event.head_commit.message }} 36 | tag_name: ${{ github.ref }} 37 | release_name: ${{ github.ref }} 38 | body: | 39 | See [CHANGES.md](https://github.com/holgerbrandl/jsonbuilder/blob/master/CHANGES.md) for new features, bug-fixes and changes. 40 | draft: false 41 | prerelease: false -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | .idea 3 | build 4 | *.gpg 5 | local.properties 6 | jsonbuilder.iml 7 | out -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: trusty 2 | 3 | language: java 4 | 5 | ## https://docs.travis-ci.com/user/languages/java 6 | ## http://stackoverflow.com/questions/20707017/how-to-run-junit-tests-with-gradle 7 | ## how to run tests with gradle https://docs.gradle.org/current/userguide/tutorial_gradle_command_line.html 8 | ## gradle check or gradle test 9 | 10 | ## http://stackoverflow.com/questions/17606874/trigger-a-travis-ci-rebuild-except-pushing-a-commit 11 | 12 | jdk: 13 | - oraclejdk8 14 | 15 | #install: gradle -q assemble 16 | 17 | sudo: required 18 | 19 | services: 20 | - docker 21 | 22 | install: 23 | #- docker pull holgerbrandl/kravis_core:3.5.1 24 | 25 | #- docker pull holgerbrandl/kravis_rserve 26 | #- docker run -dp 127.0.0.1:6311:6311 holgerbrandl/kravis_rserve 27 | #- docker ps -a 28 | 29 | 30 | #- sudo apt-get install -y r-base 31 | #- sudo chmod -R ugo+w /usr/local/lib/R/site-library 32 | #- R -e "install.packages('devtools', repos = 'http://cran.us.r-project.org')" 33 | #- R -e "install.packages('tidyverse', repos = 'http://cran.us.r-project.org')" 34 | 35 | script: gradle clean test --stacktrace --info -------------------------------------------------------------------------------- /CHANGES.md: -------------------------------------------------------------------------------- 1 | # Release History 2 | 3 | 4 | ## v0.5 5 | 6 | Initial Release -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | BSD 2-Clause License 2 | 3 | Copyright (c) 2019, Holger Brandl 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | 9 | * Redistributions of source code must retain the above copyright notice, this 10 | list of conditions and the following disclaimer. 11 | 12 | * Redistributions in binary form must reproduce the above copyright notice, 13 | this list of conditions and the following disclaimer in the documentation 14 | and/or other materials provided with the distribution. 15 | 16 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 17 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 20 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 21 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 22 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 23 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 24 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 25 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # jsonbuilder for Kotlin 2 | 3 | `jsonbuilder` is a small artifact that serves a single purpose: It allows to create json using an idiomatic [kotlin](https://kotlinlang.org/) builder DSL. 4 | 5 | ## Example 6 | 7 | ``` 8 | val myJson = json { 9 | "size" to 0 10 | "array" to arrayOf(1,2,3) 11 | "aggs" to { 12 | "num_destinations" to { 13 | "cardinality" to { 14 | "field" to "DestCountry" 15 | } 16 | } 17 | } 18 | } 19 | ``` 20 | 21 | which will result in the following json structure: 22 | ``` 23 | { 24 | "size": 0, 25 | "array": [ 26 | 1, 27 | 2, 28 | 3 29 | ], 30 | "aggs": { 31 | "num_destinations": { 32 | "cardinality": { 33 | "field": "DestCountry" 34 | } 35 | } 36 | } 37 | } 38 | ``` 39 | 40 | Both arrays and nested elements are supported without additional functions/constructs. 41 | 42 | ## Setup 43 | 44 | ### Gradle 45 | To get started simply add it as a dependency in your `build.gradle`: 46 | ``` 47 | compile "com.github.holgerbrandl:jsonbuilder:0.10" 48 | ``` 49 | 50 | ### Development Snapshots 51 | 52 | You can also use [JitPack with Maven or Gradle](https://jitpack.io/#holgerbrandl/jsonbuilder) to build the latest snapshot as a dependency in your project. 53 | 54 | ```groovy 55 | repositories { 56 | maven { url 'https://jitpack.io' } 57 | } 58 | dependencies { 59 | compile 'com.github.holgerbrandl:jsonbuilder:-SNAPSHOT' 60 | } 61 | ``` 62 | 63 | 64 | ### How to build? 65 | 66 | To build and install it into your local maven cache, simply clone the repo and run 67 | ```bash 68 | ./gradlew install 69 | ``` 70 | 71 | ## Documentation 72 | 73 | This `README.md`. Feel welcome to file tickets about missing pieces in the docs. 74 | 75 | 76 | ## How to contribute? 77 | 78 | Feel welcome to post ideas, suggestions and criticism to our [tracker](https://github.com/holgerbrandl/jsonbuilder/issues). 79 | 80 | We always welcome pull requests. :-) 81 | 82 | You could also show your spiritual support by just upvoting `jsonbuilder` here on github. 83 | 84 | ## References 85 | 86 | This library is built using https://github.com/stleary/JSON-java 87 | 88 | 89 | Other references 90 | * https://stackoverflow.com/questions/41861449/kotlin-dsl-for-creating-json-objects-without-creating-garbage 91 | * https://github.com/SalomonBrys/Kotson 92 | * 93 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | mavenCentral() 4 | } 5 | 6 | dependencies { 7 | // classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 8 | classpath 'io.codearte.gradle.nexus:gradle-nexus-staging-plugin:0.22.0' 9 | } 10 | } 11 | 12 | 13 | plugins { 14 | id "org.jetbrains.kotlin.jvm" version "1.7.20" 15 | } 16 | 17 | apply plugin: 'java' 18 | apply plugin: 'kotlin' 19 | apply plugin: 'application' 20 | //apply plugin: 'maven' 21 | apply plugin: 'maven-publish' 22 | apply plugin: 'io.codearte.nexus-staging' 23 | 24 | // not neeeded but does not work without 25 | mainClassName = "foo.Bar" // not needed but does not work without 26 | 27 | repositories { 28 | mavenCentral() 29 | mavenCentral() 30 | } 31 | 32 | 33 | dependencies { 34 | // compile "org.jetbrains.kotlin:kotlin-stdlib" 35 | 36 | // from https://github.com/stleary/JSON-java 37 | implementation 'org.json:json:20220924' 38 | 39 | testImplementation group: 'junit', name: 'junit', version: '4.12' 40 | testImplementation 'io.kotest:kotest-assertions-core:4.2.6' 41 | 42 | // needed to work around https://youtrack.jetbrains.com/issue/KT-15064 43 | // compileOnly "org.jetbrains.kotlin:kotlin-script-runtime:$kotlin_version" 44 | } 45 | 46 | // http://stackoverflow.com/questions/11474729/how-to-build-sources-jar-with-gradle 47 | task sourcesJar(type: Jar, dependsOn: classes) { 48 | classifier = 'sources' 49 | from sourceSets.main.allSource 50 | } 51 | 52 | group 'com.github.holgerbrandl' 53 | version '0.10' 54 | //version '0.10-SNAPSHOT' 55 | 56 | 57 | ext { 58 | PUBLISH_GROUP_ID = group 59 | PUBLISH_VERSION = version 60 | PUBLISH_ARTIFACT_ID = name 61 | } 62 | 63 | 64 | apply from: "${rootProject.projectDir}/publish-mavencentral.gradle" -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/holgerbrandl/jsonbuilder/28193ceadee491d7f2bc38bfa36776e5fc93ae49/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Jan 28 23:57:24 CET 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn () { 37 | echo "$*" 38 | } 39 | 40 | die () { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save () { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /publish-mavencentral.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'maven-publish' 2 | apply plugin: 'signing' 3 | 4 | java { 5 | withSourcesJar() 6 | withJavadocJar() 7 | } 8 | 9 | 10 | group = PUBLISH_GROUP_ID 11 | version = PUBLISH_VERSION 12 | 13 | ext["signing.keyId"] = '' 14 | ext["signing.password"] = '' 15 | ext["signing.secretKeyRingFile"] = '' 16 | ext["ossrhUsername"] = '' 17 | ext["ossrhPassword"] = '' 18 | ext["sonatypeStagingProfileId"] = '' 19 | 20 | File secretPropsFile = project.rootProject.file('local.properties') 21 | if (secretPropsFile.exists()) { 22 | Properties p = new Properties() 23 | p.load(new FileInputStream(secretPropsFile)) 24 | p.each { name, value -> 25 | ext[name] = value 26 | } 27 | } else { 28 | ext["signing.keyId"] = System.getenv('SIGNING_KEY_ID') 29 | ext["signing.password"] = System.getenv('SIGNING_PASSWORD') 30 | ext["signing.secretKeyRingFile"] = System.getenv('SIGNING_SECRET_KEY_RING_FILE') 31 | ext["ossrhUsername"] = System.getenv('OSSRH_USERNAME') 32 | ext["ossrhPassword"] = System.getenv('OSSRH_PASSWORD') 33 | ext["sonatypeStagingProfileId"] = System.getenv('SONATYPE_STAGING_PROFILE_ID') 34 | } 35 | 36 | publishing { 37 | publications { 38 | release(MavenPublication) { 39 | groupId PUBLISH_GROUP_ID 40 | artifactId PUBLISH_ARTIFACT_ID 41 | version PUBLISH_VERSION 42 | artifact("$buildDir/libs/${project.getName()}-${version}.jar") 43 | 44 | artifact sourcesJar 45 | artifact javadocJar 46 | 47 | pom { 48 | name = PUBLISH_ARTIFACT_ID 49 | description = 'jsonbuilder allows to build json using an idiomatic kotlin builder DSL' 50 | url = 'https://github.com/holgerbrandl/jsonbuilder' 51 | licenses { 52 | license { 53 | name = 'BSD-2' 54 | url = 'https://github.com/holgerbrandl/jsonbuilder/blob/master/LICENSE' 55 | } 56 | } 57 | developers { 58 | developer { 59 | id = 'holgerbrandl' 60 | name = 'Holger Brandl' 61 | email = 'holgerbrandl@gmail.com' 62 | } 63 | } 64 | scm { 65 | connection = 'scm:git:github.com/holgerbrandl/jsonbuilder.git' 66 | developerConnection = 'scm:git:ssh://github.com/holgerbrandl/jsonbuilder.git' 67 | url = 'https://github.com/holgerbrandl/jsonbuilder.git' 68 | } 69 | withXml { 70 | def dependenciesNode = asNode().appendNode('dependencies') 71 | 72 | project.configurations.implementation.allDependencies.each { 73 | def dependencyNode = dependenciesNode.appendNode('dependency') 74 | dependencyNode.appendNode('groupId', it.group) 75 | dependencyNode.appendNode('artifactId', it.name) 76 | dependencyNode.appendNode('version', it.version) 77 | } 78 | } 79 | } 80 | } 81 | } 82 | repositories { 83 | maven { 84 | name = "sonatype" 85 | url = "https://oss.sonatype.org/service/local/staging/deploy/maven2/" 86 | 87 | credentials { 88 | username ossrhUsername 89 | password ossrhPassword 90 | } 91 | } 92 | } 93 | } 94 | 95 | nexusStaging { 96 | packageGroup = PUBLISH_GROUP_ID 97 | stagingProfileId = sonatypeStagingProfileId 98 | username = ossrhUsername 99 | password = ossrhPassword 100 | } 101 | 102 | signing { 103 | sign publishing.publications 104 | } -------------------------------------------------------------------------------- /release_howto.md: -------------------------------------------------------------------------------- 1 | ## Release Checklist 2 | 3 | 0. Make sure to reference just public artifacts in `gradle.build` 4 | 5 | 1. Increment version in `README.md`, `gradle.build` and update [CHANGES.md](../CHANGES.md) 6 | 7 | 2. Do the release 8 | 9 | ```bash 10 | export JB_HOME=" /d/projects/misc/jsonbuilder"; 11 | 12 | trim() { while read -r line; do echo "$line"; done; } 13 | jb_version='v'$(grep '^version' ${JB_HOME}/build.gradle | cut -f2 -d' ' | tr -d "'" | trim) 14 | 15 | echo "new version is $jb_version" 16 | 17 | 18 | if [[ $jb_version == *"-SNAPSHOT" ]]; then 19 | echo "ERROR: Won't publish snapshot build $jb_version}!" 1>&2 20 | exit 1 21 | fi 22 | 23 | cd $JB_HOME 24 | 25 | git status 26 | git commit -am "${jb_version} release" 27 | #git diff --exit-code || echo "There are uncomitted changes" 28 | 29 | git tag "${jb_version}" 30 | 31 | git push origin 32 | git push origin --tags 33 | 34 | 35 | ######################################################################## 36 | ### Build and publish the binary release to maven-central 37 | 38 | ./gradlew install 39 | 40 | # careful with this one! 41 | # https://getstream.io/blog/publishing-libraries-to-mavencentral-2021/ 42 | # https://central.sonatype.org/pages/gradle.html 43 | ./gradlew publishReleasePublicationToSonatypeRepository 44 | ./gradlew closeAndReleaseRepository 45 | 46 | ## also see https://oss.sonatype.org/ 47 | ``` 48 | 49 | 3. Increment version to *-SNAPSHOT for next release cycle 50 | 51 | -------------------------------------------------------------------------------- /src/main/kotlin/com/github/holgerbrandl/jsonbuilder/JsonUtil.kt: -------------------------------------------------------------------------------- 1 | package com.github.holgerbrandl.jsonbuilder 2 | 3 | import org.json.JSONArray 4 | import org.json.JSONObject 5 | import java.util.* 6 | 7 | 8 | //Source: https://stackoverflow.com/questions/41861449/kotlin-dsl-for-creating-json-objects-without-creating-garbage 9 | 10 | 11 | fun json(build: JsonObjectBuilder.() -> Unit): JSONObject { 12 | return JsonObjectBuilder().json(build) 13 | } 14 | 15 | class JsonObjectBuilder { 16 | private val deque: Deque = ArrayDeque() 17 | 18 | fun json(build: JsonObjectBuilder.() -> Unit): JSONObject { 19 | deque.push(JSONObject()) 20 | this.build() 21 | return deque.pop() 22 | } 23 | 24 | infix fun String.to(value: T) { 25 | // wrap value into json block if it is a lambda 26 | val wrapped = when (value) { 27 | is Function0<*> -> json { value.invoke() } 28 | is Array<*> -> JSONArray().apply { value.forEach { put(it) } } 29 | else -> value 30 | } 31 | 32 | deque.peek().put(this, wrapped) 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/kotlin/Examples.kt: -------------------------------------------------------------------------------- 1 | import com.github.holgerbrandl.jsonbuilder.json 2 | 3 | object JsonTester { 4 | 5 | @JvmStatic 6 | fun main(args: Array) { 7 | val myJson = json { 8 | "size" to 0 9 | "aggs" to { 10 | "num_destinations" to { 11 | "cardinality" to { 12 | "field" to "DestCountry" 13 | } 14 | } 15 | } 16 | "array" to arrayOf(1, 2, 3) 17 | } 18 | 19 | 20 | println("json is\n${myJson.toString(2)}") 21 | } 22 | } 23 | 24 | 25 | object JsonTester2 { 26 | @JvmStatic 27 | fun main(args: Array) { 28 | val jsonObject = 29 | json { 30 | "name" to "ilkin" 31 | "age" to 37 32 | "male" to true 33 | "contact" to json { 34 | "city" to "istanbul" 35 | "email" to "xxx@yyy.com" 36 | } 37 | } 38 | println(jsonObject) 39 | 40 | 41 | } 42 | } 43 | 44 | object JsonInNestedArray { 45 | @JvmStatic 46 | fun main(args: Array) { 47 | val jsonObject = 48 | json { 49 | "foo" to "bar" 50 | "age" to 37 51 | "contacts" to arrayOf( 52 | json{ "name" to "anna"}, 53 | json{ "name" to "maria"} 54 | ) 55 | } 56 | println(jsonObject) 57 | 58 | 59 | } 60 | } -------------------------------------------------------------------------------- /src/test/kotlin/Tests.kt: -------------------------------------------------------------------------------- 1 | import com.github.holgerbrandl.jsonbuilder.json 2 | import io.kotest.matchers.shouldBe 3 | import org.json.JSONArray 4 | import org.junit.Ignore 5 | import org.junit.Test 6 | 7 | 8 | class BuilderTests { 9 | 10 | @Test 11 | @Ignore("blocked by https://github.com/stleary/JSON-java/issues/571") 12 | fun `it should preserver order`() { 13 | json { 14 | "name" to 1 15 | "type" to 1 16 | "queue" to 1 17 | "component" to 1 18 | }.toString(3).apply { 19 | println() 20 | toString() shouldBe """ 21 | { 22 | "name": 1, 23 | "type": 1, 24 | "queue": 1 25 | "component": 1, 26 | } 27 | """.trimIndent() 28 | } 29 | } 30 | 31 | // https://github.com/holgerbrandl/jsonbuilder/issues/1 32 | @Test 33 | fun `it should support root arrays`() { 34 | JSONArray(listOf( 35 | json { "foo" to "bar" }, 36 | json { "foo" to "bar" } 37 | )).println() 38 | } 39 | 40 | } 41 | 42 | internal fun Any.println() { 43 | println(toString()) 44 | } --------------------------------------------------------------------------------