我正在尝试使用JSON Form Playground从JSON中动态创建html表单,这将允许他们编辑已经存在的请求。我将请求持久化在db中的某处,并且我有映射请求类。我想将json请求转换为JSON表单请求格式。
非持久化请求
{"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中创建任何新的请求类。
发布于 2016-03-05 14:10:58
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);https://stackoverflow.com/questions/35810669
复制相似问题