项目作者: ptrbrynt

项目描述 :
A type-safe builder for JSON objects in Kotlin, using GSON
高级语言: Kotlin
项目地址: git://github.com/ptrbrynt/json-dsl.git
创建时间: 2018-09-10T13:11:45Z
项目社区:https://github.com/ptrbrynt/json-dsl

开源协议:MIT License

下载


JSON DSL


Codacy Badge
GitHub license
CircleCI (all branches)

A type-safe builder for creating JSON objects and arrays in Kotlin.

Installation

Firstly, add the JitPack repository to your project-level build.gradle file:

  1. allprojects {
  2. repositories {
  3. ...
  4. maven { url 'https://jitpack.io' }
  5. }
  6. }

Then, in your module’s build.gradle file, add the dependency:

  1. dependencies {
  2. implementation 'com.ptrbrynt:json-dsl:1.1.2'
  3. }

Usage

To create an empty JsonObject, use this syntax:

  1. val json: JsonObject = jsonObject { }

Add properties like this:

  1. val json: JsonObject = jsonObject {
  2. "my_property" to 7
  3. "another_one" to "hello"
  4. }

You can add a nested object like this:

  1. val json: JsonObject = jsonObject {
  2. "object" to jsonObject {
  3. "hello" to 7
  4. }
  5. }

You can create a JsonArray like this:

  1. val array: JsonArray = jsonArrayOf(
  2. 7,
  3. "hello",
  4. jsonObject {
  5. "a_property" to 'a'
  6. },
  7. jsonArrayOf(
  8. 2,
  9. null
  10. )
  11. )

You can add a JsonArray to a JsonObject like this:

  1. val obj: JsonObject = jsonObject {
  2. "array" to jsonArrayOf(true, "hello")
  3. }

Conversion

You can convert from a List to a JsonArray like this:

  1. val jsonArray = listOf(2, 4, 6, 623).toJsonArray()
  2. // Alternatively
  3. val jsonArray = jsonArrayOf(listOf(2, 4, 6, 623))

You can also convert a HashMap to a JsonObject:

  1. val obj = hashMapOf(Pair("hello", 7), Pair("goodbye", 12)).toJsonObject()