Create POJO Class for Kotlin

前端 未结 10 1905
闹比i
闹比i 2021-02-03 18:34

I want to create POJO class for Kotlin, as we know that www.jsonschema2pojo.org converts JSON to POJO so we can use it with gson.

Anyone know how to create Gson POJO for

相关标签:
10条回答
  • 2021-02-03 19:27

    A feature request about Kotlin support to auto generate data classes have been filled here in jsonschema2pojo github repository. Currently, there is no jsonschema2kotlin web utility available.

    If you don't have any problem installing a new plugin on Android Studio, follow the accepted answer, otherwise the best you can do is to use jsonschema2pojo to convert JSON to Java POJO and the use the Android Studio 3.0+ feature that converts a Java file to a Kotlin one.

    enter image description here

    0 讨论(0)
  • 2021-02-03 19:28

    In my case Code -> Generate doesn't work, it is disabled (see screenshot)

    You should install the plugin "JsonToKotlinClass"

    Then right-click on the namespace and select

    Paste your JSON here. That's all, profit.

    0 讨论(0)
  • 2021-02-03 19:32

    Yes, I got solution

    for Example:

    {
        "foo": "string",
        "bar": "integer",
        "baz": "boolean"
    }
    

    My POJO Class Created using http://www.jsonschema2pojo.org/

    Example.java

    public class Example {
    
        @SerializedName("foo")
        @Expose
        private String foo;
        @SerializedName("bar")
        @Expose
        private String bar;
        @SerializedName("baz")
        @Expose
        private String baz;
    
        public String getFoo() {
            return foo;
        }
    
        public void setFoo(String foo) {
            this.foo = foo;
        }
    
        public String getBar() {
            return bar;
        }
    
        public void setBar(String bar) {
            this.bar = bar;
        }
    
        public String getBaz() {
            return baz;
        }
    
        public void setBaz(String baz) {
            this.baz = baz;
        }
    }
    

    Converted Kotlin Class using Code -> Convert Java File to Kotlin File or CTRL + ALT + SHIFT + K

    Example.kt

    class Example {
    
        @SerializedName("foo")
        @Expose
        var foo: String? = null
        @SerializedName("bar")
        @Expose
        var bar: String? = null
        @SerializedName("baz")
        @Expose
        var baz: String? = null
    }
    

    Thank you all.

    0 讨论(0)
  • 2021-02-03 19:32

    In vs-code there is a plugin named Paste JSON as Code. it supports many languages. Paste Json as code

    quick look

    0 讨论(0)
提交回复
热议问题