Generating JSON from java file

2019-09-07 03:18发布

Is there a standard or existing way to generate 'something' from an uncompiled java class based on its contents? So basically something like this:

@MakeJsonDocumentation
public class ExistingClass{
    private name = "";

    public ExistingClass(String name){
        this.name = name;
    }

    @JsonField
    public String getName(){
        return this.name;
    }

    @JsonField
    public void setName(String name){
        this.name = name;
    }

    @JsonMethod
    public void someMethod(String text){
        System.out.println("someMethod " + text)
    }

    @JsonMethod
    public void otherMethod(){
        System.out.println("otherMethod")
    }
}

into something like this

{
  "ExistingClass": {
    "Fields": {
      "Name": "String"
    },
    "Methods": {
      "someMethod": {
        "Parameters": {
          "Type": "String",
          "Name": "text"
        },
        "Returns": "Nothing"
      },
      "otherMethod": {
        "Parameters": "Nothing",
        "Returns": {
          "Type": "String"
        }
      }
    }
  }
}

And if there isn't, is it possible to do this with compile-time annotations because I'd like to automate the generation instead of having to write a parser and everytime I change something about a class throw it through the parser in order to get an up-to-date datasheet.

I'm kind of in the dark here, I only know what I want but no idea how to accomplish it, so at very least some search-keywords into the right direction would be very welcome :p

2条回答
太酷不给撩
2楼-- · 2019-09-07 03:54

How about this?
https://jersey.java.net/documentation/1.17/json.html

Here's an older post that might help as well: Json - Java Object to Json

Cheers .t.

查看更多
可以哭但决不认输i
3楼-- · 2019-09-07 04:03

To achieve Json you posted above you can by:

  • use reflection to extract all fields names and methods
  • use JSONObject (json parser/builder)

from an uncompiled java class

However, reflection works with instances (or all fields/methods must be static)

查看更多
登录 后发表回答