2016-03-05 74 views
0

我想用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中創建任何新的請求類。

+0

您是要優化這個還是打開使用GSON庫 –

+0

我打算使用gson庫。 – OneMoreError

回答

0

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); 
+0

你在哪裏爲每個字段設置「type」,「title」,「default」? – OneMoreError

+0

這將是一個單獨的模型。您只需設置所有模型,然後在整個應用程序中輕鬆完成 –