A specific format represent file directory in Json

Overview

CascadeJson.kt

A specific format represent file directory in Json

Provide a function for convert to map or json string in Kotlin

Usage

Download zip file in Release, unzip it, put into ~/.m2/repository/

In your build.gradle.kts

repositories {
    ...
    mavenLocal()
}

dependencies {
    ...
    implementation("cwksc:CascadeJsonKt-jvm:0.0.1")
}

Interface

fromStringToMap(jsonString: String):        MutableMap<String, String>
fromStringToJsonString(jsonString: String): String

Example

Input:

{
    "file1": "value1",
    "file2": "value2",
    "dir1": {
        "file3": "value3",
        "file4": "value4"
    },
    "dir2": ["dir2-key", {
        "file5": "value5",
        "file6": "value6",
        "dir3" : {
            "file7": "value7",
            "file8": "value8"
        }
    }]
}

Convert by fromStringToMap:

mapOf(
    "file1" to "value1",
    "file2" to "value2",
    "dir1/file3" to "value3",
    "dir1/file4" to "value4",
    "dir2/" to "dir2-key",
    "dir2/file5" to "value5",
    "dir2/file6" to "value6",
    "dir2/dir3/file7" to "value7",
    "dir2/dir3/file8" to "value8"
)

Convert by fromStringToJsonString:

{"file1":"value1","file2":"value2","dir1/file3":"value3","dir1/file4":"value4","dir2/":"dir2-key","dir2/file5":"value5","dir2/file6":"value6","dir2/dir3/file7":"value7","dir2/dir3/file8":"value8"}

Implementation

() val layers = mutableListOf () fun dfs(jsonElement: JsonElement) { when (jsonElement) { is JsonObject -> { jsonElement.forEach { (key, value) -> layers.add(key) dfs(value) layers.removeLast() } } is JsonPrimitive -> { result[layers.joinToString("/")] = jsonElement.content } is JsonArray -> { if (jsonElement.size != 2) { throw IllegalArgumentException("Unexpected JsonArray format") } val (directoryKey, jsonObject) = jsonElement result[layers.joinToString("/") + "/"] = directoryKey.jsonPrimitive.content dfs(jsonObject) } } } dfs(json.jsonObject) return result } fun fromStringToJsonString(jsonString: String): String { return Json.encodeToString(fromStringToMap(jsonString)) }">
fun fromStringToMap(jsonString: String): MutableMap<String, String> {
    if (jsonString.isEmpty()) throw IllegalArgumentException("jsonString is empty")
    if (jsonString == "{}") return mutableMapOf()

    val json = Json.parseToJsonElement(jsonString)
    if (json !is JsonObject) throw IllegalArgumentException("jsonString is not a JsonObject")

    val result = mutableMapOf<String, String>()
    val layers = mutableListOf<String>()

    fun dfs(jsonElement: JsonElement) {
        when (jsonElement) {
            is JsonObject -> {
                jsonElement.forEach { (key, value) ->
                    layers.add(key)
                    dfs(value)
                    layers.removeLast()
                }
            }
            is JsonPrimitive -> {
                result[layers.joinToString("/")] = jsonElement.content
            }
            is JsonArray -> {
                if (jsonElement.size != 2) {
                    throw IllegalArgumentException("Unexpected JsonArray format")
                }
                val (directoryKey, jsonObject) = jsonElement
                result[layers.joinToString("/") + "/"] = directoryKey.jsonPrimitive.content
                dfs(jsonObject)
            }
        }
    }

    dfs(json.jsonObject)
    return result
}

fun fromStringToJsonString(jsonString: String): String {
    return Json.encodeToString(fromStringToMap(jsonString))
}

Project environment

Open folder CascadeJsonKt/ by IntelliJ IDEA

License

MIT

You might also like...
This directory contains the model files (protos) for the Bar ServiceThis directory contains the model files (protos) for the Bar Service
This directory contains the model files (protos) for the Bar ServiceThis directory contains the model files (protos) for the Bar Service

This directory contains the model files (protos) for the Bar ServiceThis directory contains the model files (protos) for the Bar Service

Android Material Json Form Wizard is a library for creating beautiful form based wizards within your app just by defining json in a particular format.
Android Material Json Form Wizard is a library for creating beautiful form based wizards within your app just by defining json in a particular format.

Android Json Wizard Android Json Wizard is a library for creating beautiful form based wizards within your app just by defining json in a particular f

A simple file/ directory picker dialog for android
A simple file/ directory picker dialog for android

FileListerDialog FileListerDialog helps you to list and pick file/directory. Library is built for Android Getting Started Installing To use this libra

A file/directory-picker for android. Implemented as a library project.
A file/directory-picker for android. Implemented as a library project.

Note: avoid using as SD-card file picker on Kitkat+ In Kitkat or above, use Android's built-in file-picker instead. Google has restricted the ability

PasswordStrengthView - an android library to represent password strength.
PasswordStrengthView - an android library to represent password strength.

PasswordStrengthView - an android library to represent password strength.

Movies App represent a list of movies, list of categories, search about movie and Save movie in Room Database

What is this project? Movies App represent a list of movies, list of categories, search about movie and Save movie in Room Database Main Features Kotl

Mock your datas for Okhttp and Retrofit in json format in just a few moves

okhttp-json-mock This simple library helps you mock your data for using with okhttp+retrofit in json format in just a few moves. it forwards the reque

AXrLottie (Android) Renders animations and vectors exported in the bodymovin JSON format. (Using rLottie)
AXrLottie (Android) Renders animations and vectors exported in the bodymovin JSON format. (Using rLottie)

AXrLottie (Android) Renders animations and vectors exported in the bodymovin JSON format. (Using rLottie)

A podcast proxy that sits between itunes search api and android apps allowing normalization of rss feeds to standard Json format that can be consumed by apps.

Podcasts Rss Feeds Search Proxy A podcast proxy written using kotlin dsl that sits between itunes search api, podcasts rss feeds and android apps allo

Slime loader is a map loader & saver for the file format Slime as specified here implemented in Minestom.

🗺️ SlimeLoader Slime loader is a map loader & saver for the file format Slime as specified here implemented in Minestom. Features: World loading Bloc

A directory chooser library for Android.
A directory chooser library for Android.

Android DirectoryChooser A simple directory chooser you can integrate into your Android app. This version of the library has no additional dependencie

A set of web-based tools for generating graphics and other assets that would eventually be in an Android application's res/ directory.

Android Asset Studio Open the Android Asset Studio See the older version if you're having trouble with the new version A web-based set of tools for ge

🚀Plugin for Android Studio And IntelliJ Idea to generate Kotlin data class code from JSON text ( Json to Kotlin )
🚀Plugin for Android Studio And IntelliJ Idea to generate Kotlin data class code from JSON text ( Json to Kotlin )

JsonToKotlinClass Hi, Welcome! This is a plugin to generate Kotlin data class from JSON string, in another word, a plugin that converts JSON string to

 Images grid JSON | Сетка изображений JSON
Images grid JSON | Сетка изображений JSON

Images grid JSON | Сетка изображений JSON Задача Разработать приложение: Приложение должно получать JSON-список ссылок на изображения с сервера по адр

Dynamic-UI-From-JSON - A Sample Android app to show dynamic UI generation from Json
Dynamic-UI-From-JSON - A Sample Android app to show dynamic UI generation from Json

Dynamic UI from JSON Functionality The app's functionality includes: The app gen

Pulls notifications from a remote JSON file and shows them in your app.
Pulls notifications from a remote JSON file and shows them in your app.

android-remote-notifications A Google GCM/Amazon SNS alternative using pull instead of push. Main features Independent user notifications (no Google G

xls2json - Read in Excel file (.xls, .xlsx, .xlsm) and output JSON

xls2json Read in Excel file (.xls, .xlsx, .xlsm) and output JSON. Evaluates formulas where possible. Preserve type information from Excel via JSON typ

Gradle-i18n-plugin is meant for generating a JSON file with internationalized texts, based on a Google Sheet.
Gradle-i18n-plugin is meant for generating a JSON file with internationalized texts, based on a Google Sheet.

Gradle-i18n-plugin Gradle-i18n-plugin is meant for generating a JSON file with internationalized texts, based on a Google Sheet. The plugin assumes th

Quote-App-Kotlin - Quote App Based on MVVM clean architecture getting quote from json file stored in assets

Quotify - Simple Quotes App This app shows the use of ViewModel and ViewModelFac

Owner
CWKSC
(,,・ω・,,)
CWKSC
Add page & limit as GET parameter to get all titans data in a paginated format

Add page & limit as GET parameter to get all titans data in a paginated format (default values : page=1 and limit=3). Here the page param is the page number which you require and limit is the maximum number of items per page. Sample Request :

krishna chaitanya 1 Jan 31, 2022
A TODO list app with location reminders that remind the user to do something when the user is at a specific location

Project Title Location Reminder Getting Started A TODO list app with location reminders that remind the user to do something when the user is at a spe

Raghav Saboo 0 Dec 5, 2021
Counterpart of onTouchEvent for Jetpack Compose and transform gesture with specific number of pointers

Counterpart of onTouchEvent for Jetpack Compose and transform gestures notify when last pointer is up number of pointer that are down or list of pointers that can be used to get details of events when gesture is on

Smart Tool Factory 19 Nov 19, 2022
BooksApp - Show the books list from an API with using retrofit2, picasso and JSON libraries

BooksApp Books App Show the books list from an API with using retrofit2, picasso

null 0 Jan 3, 2022
A demo project which demonstrates the work of javax.servlet.Filter capable of escaping / modifying / removing a part of JSON request based on specified criteria.

Replace Filter Demo A demo project which demonstrates the work of javax.servlet.Filter capable of escaping / modifying / removing a part of JSON reque

Vlad Krava 1 Jan 17, 2022
This repository demonstrates how Kotlin can simplify Spring Boot configuration properties file mapping

Kotlin spring-boot nested config props This repository demonstrates how Kotlin can simplify Spring Boot configuration properties file mapping @Constru

Maksim Kostromin 1 Oct 11, 2021
Example project for using the Selenium toolkit with Kotlin, Maven, TestNg and the config is managed via a property file.

Selenium-Java-Toolkit-TestNg-Playground This is the sample-Project and show you how to use the Selenium-Toolkit. The Selenium-Toolkit is a Java based

Selenium Consulting 0 Dec 15, 2021
Kotlin multi-platform simple File I/O library

KmpIO This is a Kotlin multiplatform (KMP) library for basic Text file, Binary file, and zip/archive file IO. It was initially implemented with the an

Steven K Olson 9 Oct 1, 2022
Alternative to DreamStorageService, but instead of storing files on a database, it is stored on the file system itself.

EtherealGambi Alternative to DreamStorageService, but instead of storing files on a database, it is stored on the file system itself. I made this beca

null 1 Jun 2, 2022
Intellij plugin to decode base64 encoded values in yaml file.

yaml-base64-decoder Plugin Description Extension Adds Decode Base64 Values to editor popup menu when yaml file is opened Adds a keyboard shortcut ⌥ ⇧

null 2 Dec 16, 2022