创建JSON JFORM请求
我想用JSON Form Playground从JSON动态创建html表单,这将允许他们编辑已经存在的请求。我有请求保持在db的某个地方,我有映射请求类。我想将json请求转换为JSON Form请求格式。创建JSON JFORM请求
防爆 - 持久化的请求
{"message":"My message","author":{"name":"author name","gender":"male","magic":36}}
映射类
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
}
}
我创建的上述请求,其被持久化为如下:从上述
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:
{
"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中创建任何新的请求类。
https://github.com/google/gson
您可以使用模型内的模型来实现你所需要的。
所有你需要做的就是使用GSON如下
@SerializedName("schema")
private Schema schema;
而且你的Schema对象会像
@SerializedName("message")
private Message message;
@SerializedName("author")
private Author author;
-- and so on
使用下面的代码从JSON获取对象序列化数据
Gson gson=new Gson();
Model yourModel=gson.fromJson(<your json object as string>);
使用以下代码从对象中获取json字符串
Gson gson=new Gson();
String string=gson.toJson(yourObject,YourObject.class);
你在哪里为每个字段设置“type”,“title”,“default”? – OneMoreError
这将是一个单独的模型。您只需设置所有模型,然后在整个应用程序中轻松完成 –
您是要优化这个还是打开使用GSON库 –
我打算使用gson库。 – OneMoreError