首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >创建JSON JFORM请求

创建JSON JFORM请求
EN

Stack Overflow用户
提问于 2016-03-05 13:57:17
回答 1查看 39关注 0票数 0

我正在尝试使用JSON Form Playground从JSON中动态创建html表单,这将允许他们编辑已经存在的请求。我将请求持久化在db中的某处,并且我有映射请求类。我想将json请求转换为JSON表单请求格式。

非持久化请求

代码语言:javascript
复制
{"message":"My message","author":{"name":"author name","gender":"male","magic":36}}

映射类

代码语言:javascript
复制
public class DummyRequest
{
    @SerializedName("message")
    private String message;

    @SerializedName("author")
    private Author author;

    // constructors, getters and setters ommitted 
    public static class Author
    {
        @SerializedName("name")
        private String name;

        @SerializedName("gender")
        private Gender gender;

        @SerializedName("magic")
        private Integer magic;
    }

    public static enum Gender
    {
        male, female, alien
    }
}

我创建了上面的请求,它被持久化如下:

代码语言:javascript
复制
public static void main(String[] args)
    {
        DummyRequest dummyRequest = new DummyRequest();
        dummyRequest.setMessage("My message");
        DummyRequest.Author author = new DummyRequest.Author("author name", DummyRequest.Gender.male, 36);
        dummyRequest.setAuthor(author );
        String dummyRequestJson = new Gson().toJson(dummyRequest);
        System.out.println(dummyRequestJson);
    }

现在,从上面的内容开始,我想创建一个如下格式的JSON:

代码语言:javascript
复制
{
  "schema": {
    "message": {
      "type": "string",
      "title": "Message",
      "default": "My message"
    },
    "author": {
      "type": "object",
      "title": "Author",
      "properties": {
        "name": {
          "type": "string",
          "title": "Name"
        },
        "gender": {
          "type": "string",
          "title": "Gender",
          "enum": [ "male", "female", "alien" ]
        },
        "magic": {
          "type": "integer",
          "title": "Magic number",
          "default": 42
        }
      },
      "default": {"name": "Author name", "gender": "alien", "magic": 36}
    }
  }
}

如果我使用暴力的方式,这似乎相当复杂和乏味。有人可以指导我如何继续下去吗?我不想在Java中创建任何新的请求类。

EN

回答 1

Stack Overflow用户

发布于 2016-03-05 14:10:58

https://github.com/google/gson

您可以在模型中使用模型来实现所需的功能。

您所需要做的就是使用gson序列化数据,如下所示

代码语言:javascript
复制
     @SerializedName("schema")
       private Schema schema;

您的Schema对象将如下所示

代码语言:javascript
复制
       @SerializedName("message")
       private Message message;
       @SerializedName("author")
       private Author author;
           -- and so on

使用以下代码从json获取对象

代码语言:javascript
复制
    Gson gson=new Gson();
    Model yourModel=gson.fromJson(<your json object as string>);

使用下面的代码从对象中获取json字符串

代码语言:javascript
复制
    Gson gson=new Gson();
    String string=gson.toJson(yourObject,YourObject.class);
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35810669

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档