从java文件生成JSON [英] Generating JSON from java file

查看:24
本文介绍了从java文件生成JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有标准或现有的方法可以根据未编译的 java 类的内容生成某物"?所以基本上是这样的:

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")
    }
}

变成这样

{
  "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.

我在这里有点不知所措,我只知道我想要什么但不知道如何实现它,因此至少非常欢迎一些搜索关键字进入正确的方向:p

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

推荐答案

要实现上面发布的 Json,您可以通过:

To achieve Json you posted above you can by:

  • 使用反射提取所有字段名称和方法
  • 使用 JSONObject(json 解析器/构建器)

来自未编译的 java 类

from an uncompiled java class

但是,反射适用于实例(或所有字段/方法必须是静态的)

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

这篇关于从java文件生成JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆