Search code examples
javajsonreflectionannotationsdocumentation-generation

Generating JSON from java file


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


Solution

  • 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)