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

Overview

JsonToKotlinClass

Build Status GitHub release GitHub stars JetBrains Plugin Download GitHub closed issues license

Kotlin IntelliJ Idea Plugin Android Studio Plugin

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 Kotlin data class (Json to Kotlin). We also have a Java/Kotlin library. With this you can generate Kotlin data class from JSON string programmatically.

implementation 'wu.seal.jsontokotlin:library:3.6.1'

Overview

This is a very cool tool for Kotlin developers, it can convert a JSON string to Kotlin data class. The tool could not only recognize the primitive types but also auto create complex types. It's easily accessible, we provide shortcut keymap ALT + K for Windows and Option + K for Mac, have a try and you'll fall in love with it! JsonToKotlinClass just makes programming more enjoyable, enjoy coding!

Easy Use

alt text

Want to generate classes code in inner class model? Do like this.

alt text

Want to generate Kotlin data class file directory? Do like this.

alt text

Want to generate Kotlin data classes in single file directory? Do like this.

alt text

Usage

  • Search 'JsonToKotlinClass' in Intellij Idea Plugin Repository Or AndroidStudio Plugin Repository And Install it.

File --> Settings --> Plugins --> Browse Repositories --> Search JsonToKotlinClass

  • Restart your IDE

  • Press ALT + K for Windows or Option + K for Mac or right click on package -> New->Kotlin data clas file from JSON and continue as guided.

Advanced usage

Have a try with the advanced dialog 😜

Features

Generate Example

This is the example JSON from json.org

{
    "glossary":{
        "title":"example glossary",
        "GlossDiv":{
            "title":"S",
            "GlossList":{
                "GlossEntry":{
                    "ID":"SGML",
                    "SortAs":"SGML",
                    "GlossTerm":"Standard Generalized Markup Language",
                    "Acronym":"SGML",
                    "Abbrev":"ISO 8879:1986",
                    "GlossDef":{
                        "para":"A meta-markup language, used to create markup languages such as DocBook.",
                        "GlossSeeAlso":[
                            "GML",
                            "XML"
                        ]
                    },
                    "GlossSee":"markup"
                }
            }
        }
    }
}

And with this plugin converting, Kotlin data classes would generate like this by default

data class Example(
    val glossary: Glossary
)

data class Glossary(
    val GlossDiv: GlossDiv,
    val title: String
)

data class GlossDiv(
    val GlossList: GlossList,
    val title: String
)

data class GlossList(
    val GlossEntry: GlossEntry
)

data class GlossEntry(
    val Abbrev: String,
    val Acronym: String,
    val GlossDef: GlossDef,
    val GlossSee: String,
    val GlossTerm: String,
    val ID: String,
    val SortAs: String
)

data class GlossDef(
    val GlossSeeAlso: List<String>,
    val para: String
)

Build From Source

Want to try out the newest features?

$ git clone https://github.com/wuseal/JsonToKotlinClass
$ cd JsonToKotlinClass
$ ./gradlew buildPlugin

And you're done! Go to directory build/distributions and you'll find JsonToKotlinClass-x.x.zip, which can be installed via Install plugin from disk....

Contribute to This Repo

Find it useful and want to contribute? All sorts of contributions are welcome, including but not limited to:

  • Open an issue here if you find a bug;

  • Help test the EAP version and report bugs:

Go to the "Plugins" settings, click "Browse repositories..." => "Manage repositories..." and click the "+" button to add the EAP channel repository URL "https://plugins.jetbrains.com/plugins/eap/list". Optionally, you can also add the Alpha and Beta channel repository URLs "https://plugins.jetbrains.com/plugins/alpha/list" and "https://plugins.jetbrains.com/plugins/beta/list".

Kindly note that the "EAP" or "Alpha" or "Beta" channel update may be unstable and tend to be buggy, if you want to get back to the stable version, remove the "EAP" or "Alpha" or "Beta" version and reinstall this plugin from the "JetBrains Plugin Repository" channel, which can be filtered by the drop-down menu next to the search input field.

  • Contribute your code:
$ git clone https://github.com/wuseal/JsonToKotlinClass
$ cd JsonToKotlinClass

Open the build.gradle in IntelliJ, open "Gradle" tool window, expand the project view to "JsonToKotlinClass | Tasks | intellij | runIde", right-click and choose "Debug ...", and you're done! Create your PR here!

Chinese Detail Document (中文文档)

Others

  • Any kind of issues are welcome.
  • Pull Requests are highly appreciated.

Thanks

  • Thank @davidbilik for giving me the first awesome advice.
  • Thank @cgoodroe for opening many awesome issues for me, help me improve myself
  • Thank @wangzhenguang for reminding me of the details of the problem
  • Thank @kezhenxu94 for introducing CI/CD to save me a lot of time :)
  • Thank iqbalhood for contributing logo for this project
  • Thank akindone for adding order by alphabetical feature for JsonToKotlinClass
  • Thank rafalbednarczuk for adding make keyword property valid feature for JsonToKotlinClass

Find it useful ? ❤️

  • Support and encourage me by clicking the button on the upper right of this page. ✌️
  • Share to others to help more people have a better develope expierience ❤️

Authors

This project exists thanks to all the people who contribute.

Acknowledgement

The development of this plugin is powerly driven by JetBrains.

Join the Community

Let's talk
Join JsonToKotlinClass Slack
Join JsonToKotlinClass Telegram

Note:

We analytics anonymous user behavior for improving plugin production, If you don't want this behavior enable, please contact us, we will provide a switch case for that.

Stargazers over time

Stargazers over time

Comments
  • The Moshi converter option doesn't support moshi-codegen

    The Moshi converter option doesn't support moshi-codegen

    Hi, this plugin is super awesome but I found this bug today where all of the annotated properties in my generated model failed to be deserialised. As of the way the classes are generated today, one needs to use the KotlinJsonAdapterFactory:

    .addConverterFactory(MoshiConverterFactory.create(Moshi.Builder().add(KotlinJsonAdapterFactory()).build()))
    

    i.e. adding a dependency to kotlin-reflect, a considerably heavy library. It would be nice to just do:

    .addConverterFactory(MoshiConverterFactory.create())
    

    @tfcporciuncula pointed me to a simple solution which is using the more explicit annotation @field:Json instead of simply @Json.

    EDIT: however that is NOT a recommended solution! It would work with these Gradle dependencies:

    implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
    implementation "com.squareup.retrofit2:converter-moshi:$retrofitVersion"
    implementation 'com.squareup.moshi:moshi-kotlin:1.6.0'
    

    By supporting the moshi codegen, the need of KotlinJsonAdapterFactory can be removed and the simple annotation @Json can be kept, one just needs to annotate the class with @JsonClass(generateAdapter = true) and update the dependencies to:

    implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
    implementation "com.squareup.retrofit2:converter-moshi:$retrofitVersion"
    implementation "com.squareup.moshi:moshi:$moshiVersion"
    kapt "com.squareup.moshi:moshi-kotlin-codegen:$moshiVersion"
    
    enhancement 
    opened by gobetti 18
  • fields with null value are given the non nullable type Any

    fields with null value are given the non nullable type Any

    Jsons that contain fields with null value could not be parsed with the generated model due to the fields being assigned the non nullable type Any. I think Any? is more appropriate.

    example: json: { "_id": null, "name": "test", "type": "test" } is parsed to data class test( @Json(name = "_id") val id: Any, //null @Json(name = "name") val name: String, //test @Json(name = "type") val type: String //test )

    enhancement help wanted awesome advice 
    opened by saied89 17
  • File Already Exists

    File Already Exists

    PluginVersion:3.0.1 User Config:

    {
      "uuid": "a1b5882e-ec6d-4567-823e-5e0cf5505958",
      "pluginVersion": "3.0.1",
      "isPropertiesVar": false,
      "isCommentOff": true,
      "isOrderByAlphabetical": true,
      "propertyTypeStrategy": "AutoDeterMineNullableOrNot",
      "initWithDefaultValue": false,
      "targetJsonConverterLib": "Gson",
      "isInnerClassMode": false,
      "customAnnotationImportClassString": "import kotlinx.serialization.SerialName\nimport kotlinx.serialization.Serializable\nimport kotlinx.serialization.Optional",
      "customClassAnnotationFormatString": "@Serializable",
      "customPropertyAnnotationFormatString": "@Optional\n@SerialName(\"%s\")",
      "enableMapType": false,
      "enableAutoReformat": true,
      "enableMinimalAnnotation": false,
      "parenClassTemplate": "",
      "keywordPropertyValid": true,
      "extensionsConfig": "",
      "timeStamp": "1553474343902",
      "daytime": "2019-03-24"
    }
    
    com.intellij.util.IncorrectOperationException: Cannot create file 'C:\src\training-master\app\src\main\java\com\example\post_sample\Model\user.kt'. File already exists.
    	at com.intellij.psi.impl.file.PsiDirectoryImpl.checkName(PsiDirectoryImpl.java:465)
    	at com.intellij.psi.impl.file.PsiDirectoryImpl.checkAdd(PsiDirectoryImpl.java:454)
    	at com.intellij.psi.impl.file.PsiJavaDirectoryImpl.checkAdd(PsiJavaDirectoryImpl.java:80)
    	at com.intellij.psi.impl.file.PsiDirectoryImpl.add(PsiDirectoryImpl.java:393)
    	at com.intellij.psi.impl.file.PsiJavaDirectoryImpl.add(PsiJavaDirectoryImpl.java:65)
    	at wu.seal.jsontokotlin.utils.KotlinDataClassFileGenerator$generateKotlinDataClassFile$1.invoke(KotlinDataClassFileGenerator.kt:234)
    	at wu.seal.jsontokotlin.utils.KotlinDataClassFileGenerator$generateKotlinDataClassFile$1.invoke(KotlinDataClassFileGenerator.kt:21)
    	at wu.seal.jsontokotlin.utils.SimplifiedMethodsKt$executeCouldRollBackAction$1$1.run(SimplifiedMethods.kt:26)
    	at com.intellij.openapi.application.impl.ApplicationImpl.runWriteAction(ApplicationImpl.java:1038)
    	at wu.seal.jsontokotlin.utils.SimplifiedMethodsKt$executeCouldRollBackAction$1.run(SimplifiedMethods.kt:25)
    	at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(CoreCommandProcessor.java:139)
    	at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(CoreCommandProcessor.java:97)
    	at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(CoreCommandProcessor.java:87)
    	at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(CoreCommandProcessor.java:73)
    	at wu.seal.jsontokotlin.utils.SimplifiedMethodsKt.executeCouldRollBackAction(SimplifiedMethods.kt:24)
    	at wu.seal.jsontokotlin.utils.KotlinDataClassFileGenerator.generateKotlinDataClassFile(KotlinDataClassFileGenerator.kt:231)
    	at wu.seal.jsontokotlin.utils.KotlinDataClassFileGenerator.generateMultipleDataClassFiles(KotlinDataClassFileGenerator.kt:66)
    	at wu.seal.jsontokotlin.GenerateKotlinFileAction.doGenerateKotlinDataClassFileAction(GenerateKotlinFileAction.kt:101)
    	at wu.seal.jsontokotlin.GenerateKotlinFileAction.actionPerformed(GenerateKotlinFileAction.kt:63)
    	at com.intellij.openapi.actionSystem.ex.ActionUtil$1.run(ActionUtil.java:255)
    	at com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAware(ActionUtil.java:272)
    	at com.intellij.openapi.actionSystem.impl.ActionMenuItem$ActionTransmitter.lambda$actionPerformed$0(ActionMenuItem.java:304)
    	at com.intellij.openapi.wm.impl.FocusManagerImpl.runOnOwnContext(FocusManagerImpl.java:307)
    	at com.intellij.openapi.wm.impl.IdeFocusManagerImpl.runOnOwnContext(IdeFocusManagerImpl.java:106)
    	at com.intellij.openapi.actionSystem.impl.ActionMenuItem$ActionTransmitter.actionPerformed(ActionMenuItem.java:294)
    	at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    	at com.intellij.openapi.actionSystem.impl.ActionMenuItem.lambda$fireActionPerformed$0(ActionMenuItem.java:114)
    	at com.intellij.openapi.application.TransactionGuardImpl.runSyncTransaction(TransactionGuardImpl.java:88)
    	at com.intellij.openapi.application.TransactionGuardImpl.lambda$submitTransaction$1(TransactionGuardImpl.java:111)
    	at com.intellij.openapi.application.TransactionGuardImpl.submitTransaction(TransactionGuardImpl.java:120)
    	at com.intellij.openapi.application.TransactionGuard.submitTransaction(TransactionGuard.java:122)
    	at com.intellij.openapi.actionSystem.impl.ActionMenuItem.fireActionPerformed(ActionMenuItem.java:114)
    	at com.intellij.ui.plaf.beg.BegMenuItemUI.doClick(BegMenuItemUI.java:529)
    	at com.intellij.ui.plaf.beg.BegMenuItemUI.access$300(BegMenuItemUI.java:49)
    	at com.intellij.ui.plaf.beg.BegMenuItemUI$MyMouseInputHandler.mouseReleased(BegMenuItemUI.java:549)
    	at java.awt.Component.processMouseEvent(Component.java:6548)
    	at javax.swing.JComponent.processMouseEvent(JComponent.java:3325)
    	at java.awt.Component.processEvent(Component.java:6313)
    	at java.awt.Container.processEvent(Container.java:2237)
    	at java.awt.Component.dispatchEventImpl(Component.java:4903)
    	at java.awt.Container.dispatchEventImpl(Container.java:2295)
    	at java.awt.Component.dispatchEvent(Component.java:4725)
    	at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4889)
    	at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4526)
    	at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4467)
    	at java.awt.Container.dispatchEventImpl(Container.java:2281)
    	at java.awt.Window.dispatchEventImpl(Window.java:2746)
    	at java.awt.Component.dispatchEvent(Component.java:4725)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:764)
    	at java.awt.EventQueue.access$500(EventQueue.java:98)
    	at java.awt.EventQueue$3.run(EventQueue.java:715)
    	at java.awt.EventQueue$3.run(EventQueue.java:709)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90)
    	at java.awt.EventQueue$4.run(EventQueue.java:737)
    	at java.awt.EventQueue$4.run(EventQueue.java:735)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:734)
    	at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:817)
    	at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:754)
    	at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:394)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
    

    Error Json String:

    {
        "user": {
            "id": 29,
            "google_id": null,
            "name": "snoop",
            "email": "[email protected]",
            "image": null,
            "category_id": 1,
            "created_at": "2019-03-22 19:05:33",
            "updated_at": "2019-03-22 19:05:33"
        }
    }
    
    bug 
    opened by wuseal 13
  • Fix issue#82

    Fix issue#82

    #82 Fix issue

    Change: Reused KotlinDataClassFileGenerator() and changed the flow to create the list of non duplicate classes for inclass JsonToKotlin Conversion

    opened by Karthik2007 13
  • Use required-attribute of JSON Schema file.

    Use required-attribute of JSON Schema file.

    Hey people!

    If i have a JSON Schema like the following one. I want that the only required attribute in my Kotlin data class is the title and not the subtitle.

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "type": "object",
      "properties": {
        "title": {
          "type": "string"
        },
        "subtitle": {
          "type": "string"
        }
      },
      "required": [
        "title"
      ]
    }
    

    i expect a generated Kotlin data class like this (with a nullable subtitle)

    data class Test(
            val title: String,
            val subtitle: String?
    )
    

    but i get this one (with a non null subtitle)

    data class Test(
            val title: String,
            val subtitle: String
    )
    

    Is this feature planned?

    Thanks, Daniel

    opened by schoeda 12
  • Type String is not generated (Wrong generation)

    Type String is not generated (Wrong generation)

    In the json below:

    {
        "value": 332.32,
        "minimumValue": 25,
        "throwValue": 2112,
        "payments": [
            {
                "date": "2019-10-16T14:07:00",
                "value": {
                    "usd": 0,
                    "brl": 50
                },
                "description": "payment"
            },
            {
                "date": "2019-10-18T14:07:00",
                "value": {
                    "usd": 0,
                    "brl": 30
                },
                "description": "payment"
            }
        ],
        "previousValue": 100,
        "releasesMonths": [
            {
                "credit": false,
                "type": {
                    "code": 4,
                    "description": "PARCEL A"
                },
                "cardType": {
                    "code": 1,
                    "description": "FISIC"
                },
                "date": "2019-10-16T14:07:00",
                "segment": {
                    "code": 1,
                    "description": "segment 1"
                },
                "value": {
                    "usd": 0,
                    "brl": 500
                },
                "parcelsNumber": 0,
                "parcelsQuantity": 0,
                "finalCard": "1234",
                "description": "Store A"
            },
            {
                "credit": false,
                "type": {
                    "code": 2,
                    "description": "PARCEL B"
                },
                "cardType": {
                    "code": 1,
                    "description": "FISIC"
                },
                "date": "2019-10-10T17:32:00",
                "segment": {
                    "code": 2,
                    "description": "Segment 2"
                },
                "value": {
                    "usd": 0,
                    "brl": 300
                },
                "parcelsNumber": 1,
                "parcelsQuantity": 2,
                "finalCard": "1234",
                "description": "Store B"
            }
        ]
    }
    

    generates the kotlin below:

    package com.my.package.name
    
    data class Test(
        val value: Double? = 0.0,
        val minimumValue: Int? = 0,
        val throwValue: Int? = 0,
        val payments: List<Payment?>? = listOf(),
        val previousValue: Int? = 0,
        val releasesMonths: List<ReleasesMonth?>? = listOf()
    )
    
    data class Payment(
        val date: Date? = Date(),
        val value: Value? = Value(),
        val description: Description? = Description()
    )
    
    data class Date(
        val value: String? = ""
    )
    
    data class Value(
        val members: Members? = Members()
    )
    
    data class Members(
        val usd: Int? = 0,
        val brl: Int? = 0
    )
    
    data class Description(
        val value: String? = ""
    )
    
    data class ReleasesMonth(
        val credit: Credit? = Credit(),
        val type: Type? = Type(),
        val cardType: CardType? = CardType(),
        val date: DateX? = Date(),
        val segment: Segment? = Segment(),
        val value: ValueX? = Value(),
        val parcelsNumber: ParcelsNumber? = ParcelsNumber(),
        val parcelsQuantity: ParcelsQuantity? = ParcelsQuantity(),
        val finalCard: FinalCard? = FinalCard(),
        val description: DescriptionX? = Description()
    )
    
    data class Credit(
        val value: Boolean? = false
    )
    
    data class Type(
        val members: MembersX? = Members()
    )
    
    data class MembersX(
        val code: Int? = 0,
        val description: String? = ""
    )
    
    data class CardType(
        val members: MembersXX? = Members()
    )
    
    data class MembersXX(
        val code: Int? = 0,
        val description: String? = ""
    )
    
    data class DateX(
        val value: String? = ""
    )
    
    data class Segment(
        val members: MembersXXX? = Members()
    )
    
    data class MembersXXX(
        val code: Int? = 0,
        val description: String? = ""
    )
    
    data class ValueX(
        val members: MembersXXXX? = Members()
    )
    
    data class MembersXXXX(
        val usd: Int? = 0,
        val brl: Int? = 0
    )
    
    data class ParcelsNumber(
        val value: ValueXX? = Value()
    )
    
    data class ValueXX(
        val value: String? = ""
    )
    
    data class ParcelsQuantity(
        val value: ValueXXX? = Value()
    )
    
    data class ValueXXX(
        val value: String? = ""
    )
    
    data class FinalCard(
        val value: String? = ""
    )
    
    data class DescriptionX(
        val value: String? = ""
    )
    

    As you can see, the String is not generated directly. An object containing a string is... is it a bug? How can i generate String directly without an object?

    Another point is: Why this code is generating various duplicated classes with XX in the end? is it a bug? How can i generate only one object? without X...

    I generated the kotlin file from the .jar JsonToKotlinClassLibrary-3.5.1-alpha01.jar with:

            String kotlinCode = new JsonToKotlinBuilder()
                    .setPackageName("com.my.package.name")
                    .enableVarProperties(false)
                    .setPropertyTypeStrategy(PropertyTypeStrategy.Nullable)
                    .setDefaultValueStrategy(DefaultValueStrategy.AvoidNull)
                    .setAnnotationLib(TargetJsonConverter.None)
                    .enableOrderByAlphabetic(false)
                    .enableInnerClassModel(false)
                    .enableCreateAnnotationOnlyWhenNeeded(true)
                    .enableAnnotationAndPropertyInSameLine(true)
                    .enableParcelableSupport(true)
                    .enableForceInitDefaultValueWithOriginJsonValue(true)
                    .enableForcePrimitiveTypeNonNullable(true)
                    .build(json, jsonName);
    
    wait for feedback MaybeNotResolvedBug 
    opened by johnmarcus015 11
  • Support no parameter constructor

    Support no parameter constructor

    现在导入的时候设置Disable Kotlin Data Class可以生成普通的class,但是混淆以后仍然报错,尝试了一下,发现将构造方法改成无参的,变量都改成成员变量就好了。

    报错的例子:

    class Test (
        @JSONField(name = "a")
         var a = 0,
        @JSONField(name = "b")
        var b = listOf<Int>()
    )
    

    改成这样就好了:

    class Test {
        @JSONField(name = "a")
         var a = 0
        @JSONField(name = "b")
        var b = listOf<Int>()
    }
    

    所以,希望能增加一个配置:是否以无参构造方式生成成员变量。

    feature request L4 
    opened by Nstd 10
  • Generated model not matching JSON

    Generated model not matching JSON

    My input:

    {
    	"generic": [{
    			"name": {
    				"address": "123"
    			},
    			"call_me": "ONE"
    		},
    		{
    			"name": {
    				"address_secondary": "GO TO ACCOUNT"
    			},
    			"call_me": "TWO"
    		},
    		{
    			"name": {
    				"address_present": false
    			},
    			"call_me": "THREE"
    		},
    		{
    			"name": {
    				"none": "Bill",
    				"sure": "Gates"
    			},
    			"call_me": "FOUR"
    		}
    	]
    }
    

    Actual output:

    data class Output(
        val generic: List<Generic> = listOf()
    ) {
        data class Generic(
            val call_me: String = "",
            val name: Name = Name()
        ) {
            data class Name(
                val none: String = "",
                val sure: String = ""
            )
        }
    }
    

    Expecting something along the lines of:

    data class Output(
        val generic: List<Generic> = listOf()
    ) {
        data class Generic(
            val call_me: String = "",
            val name: Name = Name()
        ) {
            data class Name(
                val address: String = "",
                val address_secondary: String = "",
                val address_present: String = "",
                val none: String = "",
                val sure: String = ""
            )
        }
    }
    
    bug enhancement 
    opened by ColtonIdle 10
  • JsonSchema doesn't generate class

    JsonSchema doesn't generate class

    Hi there,

    I'm trying to generate a Data Class based on the following json (schema):

    {
      "$schema": "http://json-schema.org/draft-07/schema#",
      "$id": "http://example.com/product.schema.json",
      "title": "Product",
      "description": "A product from Acme's catalog",
      "type": "object",
      "properties": {
        "productId": {
          "description": "The unique identifier for a product",
          "type": "integer"
        }
      },
      "required": [ "productId" ]
    }
    

    I've already commented on the issue here: https://github.com/wuseal/JsonToKotlinClass/issues/108, but it seems to be different.

    Right now, the above code generates the following class:

    
    import com.fasterxml.jackson.annotation.JsonProperty
    
    data class JsonSchema(
        val productId: Int
    )
    

    That's all. I'm expecting a bit more. That the $id/$schema don't work, I can sort of understand, but the rest not so much.

    Could you please have a look?

    Cheers!

    enhancement 
    opened by bodiam 9
  • Making default values as values from Json with option to disable

    Making default values as values from Json with option to disable

    @wuseal I get json with values that should be taken as default values. Does it make sense to have the values set as default values to the attributes of data class in the library. May be with option to enable/disable the feature. Just thinking aloud.

    feature request L2 
    opened by Karthik2007 9
  • NoSuchElementException: null

    NoSuchElementException: null

    I get this error every time, and I know the Json is valid. Following steps just like your example, please take a look.

    Also, it looks like you're generating comments to the right of each field? Could you make this an option also?

    Thank you for working on this! It could be super useful.

    null
    java.util.NoSuchElementException
    	at java.util.ArrayList$Itr.next(ArrayList.java:854)
    	at wu.seal.jsontokotlin.KotlinMaker.getArrayType(KotlinMaker.java:92)
    	at wu.seal.jsontokotlin.KotlinMaker.appendJsonObject(KotlinMaker.java:66)
    	at wu.seal.jsontokotlin.KotlinMaker.makeKotlinData(KotlinMaker.java:38)
    	at wu.seal.jsontokotlin.KotlinMaker.getJsonObjectType(KotlinMaker.java:84)
    	at wu.seal.jsontokotlin.KotlinMaker.appendJsonObject(KotlinMaker.java:72)
    	at wu.seal.jsontokotlin.KotlinMaker.makeKotlinData(KotlinMaker.java:38)
    	at wu.seal.jsontokotlin.MakeKotlinClassAction$3$1.run(MakeKotlinClassAction.java:143)
    	at com.intellij.openapi.application.impl.ApplicationImpl.runWriteAction(ApplicationImpl.java:898)
    	at wu.seal.jsontokotlin.MakeKotlinClassAction$3.run(MakeKotlinClassAction.java:131)
    	at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(CoreCommandProcessor.java:129)
    	at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(CoreCommandProcessor.java:100)
    	at com.intellij.openapi.command.impl.CoreCommandProcessor.executeCommand(CoreCommandProcessor.java:86)
    	at wu.seal.jsontokotlin.MakeKotlinClassAction.actionPerformed(MakeKotlinClassAction.java:128)
    	at com.intellij.openapi.actionSystem.ex.ActionUtil$1.run(ActionUtil.java:197)
    	at com.intellij.openapi.application.TransactionGuardImpl.runSyncTransaction(TransactionGuardImpl.java:88)
    	at com.intellij.openapi.application.TransactionGuardImpl.submitTransactionAndWait(TransactionGuardImpl.java:156)
    	at com.intellij.openapi.actionSystem.ex.ActionUtil.performActionDumbAware(ActionUtil.java:211)
    	at com.intellij.ui.popup.PopupFactoryImpl$ActionPopupStep.performAction(PopupFactoryImpl.java:875)
    	at com.intellij.ui.popup.PopupFactoryImpl$ActionPopupStep.lambda$onChosen$0(PopupFactoryImpl.java:863)
    	at com.intellij.openapi.application.TransactionGuardImpl.performUserActivity(TransactionGuardImpl.java:199)
    	at com.intellij.ui.popup.AbstractPopup.lambda$null$7(AbstractPopup.java:1390)
    	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
    	at java.awt.EventQueue.access$500(EventQueue.java:97)
    	at java.awt.EventQueue$3.run(EventQueue.java:709)
    	at java.awt.EventQueue$3.run(EventQueue.java:703)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
    	at com.intellij.ide.IdeEventQueue.defaultDispatchEvent(IdeEventQueue.java:795)
    	at com.intellij.ide.IdeEventQueue._dispatchEvent(IdeEventQueue.java:631)
    	at com.intellij.ide.IdeEventQueue.dispatchEvent(IdeEventQueue.java:387)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
    
    opened by cgoodroe 9
  • "New ..." only works with json file selected

    If I want to generate code, I must select a JSON file but afterwards have to copy the content anyway. If I have any other file selected and call "New Kotlin data class File from JSON", nothing happens.

    opened by Jeansen 6
  • Enable Default Constructor Creation Option

    Enable Default Constructor Creation Option

    In the case when we want to send a class out as a Request, it would be useful to create a constructor with default arguments in some cases, which we could change later. For example, see constructor() at the bottom of this code:

    data class Activity(
        var updated_on: String,
        var tags: List<String>,
        var description: String,
        var user_id: List<Int>,
        var status_id: Int,
        var title: String,
        var created_at: String,
        var data: HashMap<*, *>,
        var id: Int,
        var counts: LinkedTreeMap<*, *>
    ) {
        constructor() : this("", emptyList(), 
                             "", emptyList(), -1, 
                             "", "", hashMapOf<Any, Any>(), 
                             -1, LinkedTreeMap<Any, Any>()
                             )
    }
    
    opened by Danc2050 1
  • camel Case format not work

    camel Case format not work

    I uninstalled and restored the plugin, using all the default Settings. Check the camel Case switch in the Settings is enable, which is on by default. The annotation format is also Gson by default. Generate the Bean without changing anything, and find that the properties in the Bean are still the same as the keys in json, without being converted to the camel Case format.

    I use the Android Studio Dolphin | 2021.3.1 Patch 1

    Build #AI-213.7172.25.2113.9123335, built on September 30, 2022 Runtime version: 11.0.13+0-b1751.21-8125866 x86_64 VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o. macOS 13.0 Memory: 2048M Cores: 16

    Non-Bundled Plugins: wu.seal.tool.jsontokotlin (3.7.4) com.jaeger.findviewbyme (1.4.3) ink.organics.pojo2json (1.2.5) com.intellij.ideolog (203.0.30.0) com.robohorse.robopojogenerator (2.3.8) com.github.copilot (1.1.35.2063) Dart (213.7433) cn.yiiguxing.plugin.translate (3.3.5) io.flutter (71.0.3) com.jetbrains.kmm (0.3.4(213-1.7.11-357-IJ)-241)

    my jsonFile like this { "whatsapp": "whatsapp:+0806", "linkloan": "www32.142.175", "linloantest": "ni-v4.117.234.851" }

    opened by Eiffelyk 2
  • For `null` properties, use JsonNode/JsonElement instead of Any

    For `null` properties, use JsonNode/JsonElement instead of Any

    Bonjour,

    your plugin is fantastic, what a waste of time it seems now to have written the data classes manually!

    I have a request:

    If my json contains a null like

    {
    "started_at": "sdfqsdds",
    "closed_at" : null
    }
    

    the plugin is currently translating to the Any? type, which gives me a runtime/compile error (don't remember).

    I would rather have those types being used, depending on my serialization library:

    val jackson: com.fasterxml.jackson.databind.JsonNode? = TODO()
    val kotlinx : kotlinx.serialization.json.JsonElement? = TODO()
    
    enhancement awesome advice 
    opened by jmfayard 1
Releases(3.7.4)
Owner
Seal
Ho lu Ho lu
Seal
The most complete and powerful data-binding library and persistence infra for Kotlin 1.3, Android & Splitties Views DSL, JavaFX & TornadoFX, JSON, JDBC & SQLite, SharedPreferences.

Lychee (ex. reactive-properties) Lychee is a library to rule all the data. ToC Approach to declaring data Properties Other data-binding libraries Prop

Mike 112 Dec 9, 2022
Android part of the Android Studio(IntellijIDEA) OkHttp Profiler plugin

OkHttpProfiler Android Library Created by LocaleBro.com - Android Localization Platform The OkHttp Profiler plugin can show requests from the OkHttp l

Ievgenii 261 Dec 8, 2022
droidparts 6.7 0.0 L5 Java DI, ORM, JSON, ...

DroidParts a carefully crafted Android framework that includes: DI - injection of Views, Fragments, Services, etc. ORM - efficient persistence utilizi

DroidParts 779 Dec 21, 2022
A data-binding Presentation Model(MVVM) framework for the Android platform.

PLEASE NOTE, THIS PROJECT IS NO LONGER BEING MAINTAINED. As personal time contraints, I am currently unable to keep up. Please use official android da

RoboBinding open source 1.3k Dec 9, 2022
Pet project using Clean Architecture + MVVM + Reactive Extensions + Android Architecture Components. The data are fetched from LondonTheatreDirect API. 🎭

Theatre Pet project using Clean Architecture + MVVM + Reactive Extensions + Android Architecture Components. The data is fetched from LondonTheatreDir

André Mion 646 Jan 9, 2023
Small Warp Plugin developed in Kotlin

Warps A small warps plugin for the 1.17 SMP. Minecraft 1.17 Spigot Contributing Install Java 16 Fork this repo Clone your fork Make your changes Use h

MenuDocs 6 Feb 19, 2022
A plugin system that runs like a browser, but instead of load web pages, it load apk plugins which runs natively on Android system.

Android Dynamic Loader Android Dynamic Loader is a plugin system. The host application is like a browser, but instead of load web pages, it load plugi

Tu Yimin 1.4k Dec 28, 2022
Android Plugin Framework

Android Plugin Framework This project is pre-mature and may be changed very frequently. Introduction Android Plugin Framework (APF) aims to providing

Umeng Limited 322 Nov 17, 2022
Gradle plugin to deploy Android Snapshot Versions

Android Snapshot Publisher is a Gradle plugin to prepare and distribute Android Snapshot versions to multiple distribution sources in a simple and com

xmartlabs 144 Nov 29, 2022
LiteOrm is a fast, small, powerful ORM framework for Android. LiteOrm makes you do CRUD operarions on SQLite database with a sigle line of code efficiently.

#LiteOrm:Android高性能数据库框架 A fast, small, powerful ORM framework for Android. LiteOrm makes you do CRUD operarions on SQLite database with a sigle line

马天宇 1.5k Nov 19, 2022
VasSonic is a lightweight and high-performance Hybrid framework developed by tencent VAS team, which is intended to speed up the first screen of websites working on Android and iOS platform.

VasSonic: A Lightweight And High-performance Hybrid Framework VasSonic is a lightweight and high-performance Hybrid framework developed by tencent VAS

Tencent 11.6k Dec 30, 2022
kotlin-core - A full framework for making Android apps. Based on Anko and Kotson.

kotlin-core This package is not Android-specific, and can be used across platforms. However, for a good example of use in Android, take a look at kotl

Lightning Kite 36 Oct 3, 2022
Android common lib, include ImageCache, HttpCache, DropDownListView, DownloadManager, Utils and so on

android-common-lib 关于我,欢迎关注 微博:Trinea 主页:trinea.cn 邮箱:trinea.cn#gmail.com 微信:codek2 主要包括:缓存(图片缓存、预取缓存、网络缓存)、公共View(下拉及底部加载更多ListView、底部加载更多ScrollView、

Trinea 5k Dec 30, 2022
A Job Queue specifically written for Android to easily schedule jobs (tasks) that run in the background, improving UX and application stability.

This Project is Deprecated! Thanks to everybody who've used Android Priority JobQueue. It was designed in a world where there was no JobScheduler, RxJ

Yigit Boyar 3.4k Dec 31, 2022
Android app built with MVP architectural approach and uses Marvel Comics API that allows developers everywhere to access information about Marvel's vast library of comics. :zap:

Villains & Heroes Android app built with MVP architectural approach and uses Marvel Comics API that allows developers everywhere to access information

André Mion 53 Jul 13, 2022
Add new features for reverse engineering, such as: renaming of classes, fields, methods, variables, reference graphs and more.

Super JADX features Add new features for reverse engineering, such as: renaming of classes, fields, methods, variables, reference graphs and more. bas

null 284 Dec 28, 2022
Source++ is an open-source live coding platform. Add breakpoints, logs, metrics, and tracing to live production applications

Source++ is an open-source live coding platform. Add breakpoints, logs, metrics, and distributed tracing to live production software in real-time on-d

Source++ 40 Dec 14, 2022
Create kotlin android project with one line of command.

README This is an android application template project built with kotlin language and some useful libraries. It provides a creator script to quickly c

nekocode 1.6k Dec 20, 2022
Cross-platform framework for building truly native mobile apps with Java or Kotlin. Write Once Run Anywhere support for iOS, Android, Desktop & Web.

Codename One - Cross Platform Native Apps with Java or Kotlin Codename One is a mobile first cross platform environment for Java and Kotlin developers

Codename One 1.4k Dec 23, 2022