简体   繁体   中英

Convert Java Data Class to Array of Fields/Metadata for frontend (Similar to Swagger Data Model/Schema)?

I currently have a bunch of Java Data Defintions that I have to duplicate the definition as a JSON array for use in a front-end table display.

Is there a standard way to generate the field, clazz, and metadata definitions from the Java Class during build (or dynamically on request)? Ideally with the option to define some other metadata via annotations?

I am thinking it could be done via getFields and Annotations, but I was hoping there was some resource available that could help me learn what is the common way to do something like this (or if this should even be done)?

eg) (With example desired Annotations)

@GenerateClassMeta
class MyObject {
    @Title("Id")
    int id;
    
    @Title("My String")
    String myStr;
   
    @Title("My List")
    List<String> list;
     
    @EmbeddedMeta(title="My Child",field="child")
    Child child;
   
}
class Child{
    @Title("Enabled")
    boolean enabled;
    
    @IgnoreMeta
    String myOtherString;        
}

And the generated JSON array would be something like

   [
       {
           "title":"Id",
           "field":"id",
           "clazz":"java.lang.Integer",
           "searchPath":"id"
       },
       {
           "title":"My String",
           "field":"myString",
           "clazz":"java.lang.String",
           "searchPath":"myStr"
       },
       {
           "title":"My List",
           "field":"list",
           "clazz":"java.util.list",
           "searchPath":"list"
        },
        {
           "title":"My Child: Enabled",
           "field":"enabled",
           "clazz":"java.lang.Boolean",
           "searchPath":"child.enabled"
        }
   ]

Currently i have to manually write the JSON definition for displaying in the front-end, but was hoping to change it so the front-end can fetch the generated metadata and format it as needed for various displays.

If it makes a difference it is for a Spring-Boot server/React frontend. The metadata is used to define (among other things) the columns and entity search paths for a datatable.

Any help would be appreciated.

Have a look at JSON Schema. There are a number of implementations that convert code to JSON Schema: https://json-schema.org/implementations.html

Of course the JSON structure is different from your example, but JSON Schema is widely used (for instance in OpenAPI).

Side note: not sure what your frontend intends to do with the data, but in case you're planning to display a dynamic form using this data, there also are a number of implementations that do just that: https://json-schema.org/implementations.html#web-ui-generation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM