2013-07-22 59 views
10

我正在使用Gson將java對象序列化/反序列化爲json。我想在UI中顯示它,並且需要一個模式來更好地描述。這將允許我編輯對象並添加比實際更多的數據。
可以Gson提供json模式嗎?
其他框架是否有這種能力?從Java類創建JSON模式

+0

你想什麼UI中顯示?我真的不知道問題是什麼。 'gson'可以將Java-Classes轉換爲JSON格式,這就是'gson'所做的。 – user1983983

回答

21

Gson庫可能不包含任何此類功能,但您可以嘗試使用Jackson庫和jackson-module-jsonSchema模塊來解決您的問題。例如,對於以下兩類:

class Entity { 

    private Long id; 
    private List<Profile> profiles; 

    // getters/setters 
} 

class Profile { 

    private String name; 
    private String value; 
    // getters/setters 
} 

此程序:

import java.io.IOException; 
import java.util.List; 

import com.fasterxml.jackson.databind.ObjectMapper; 
import com.fasterxml.jackson.module.jsonSchema.JsonSchema; 
import com.fasterxml.jackson.module.jsonSchema.factories.SchemaFactoryWrapper; 

public class JacksonProgram { 

    public static void main(String[] args) throws IOException { 
     ObjectMapper mapper = new ObjectMapper(); 
     SchemaFactoryWrapper visitor = new SchemaFactoryWrapper(); 
     mapper.acceptJsonFormatVisitor(Entity.class, visitor); 
     JsonSchema schema = visitor.finalSchema(); 
     System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(schema)); 
    } 
} 

打印模式如下:

{ 
    "type" : "object", 
    "properties" : { 
    "id" : { 
     "type" : "integer" 
    }, 
    "profiles" : { 
     "type" : "array", 
     "items" : { 
     "type" : "object", 
     "properties" : { 
      "name" : { 
      "type" : "string" 
      }, 
      "value" : { 
      "type" : "string" 
      } 
     } 
     } 
    } 
    } 
} 
+0

在「id」對象中有2個「類型」鍵!這是對的嗎?你能解釋一下嗎?謝謝 – thermz

+0

我不知道爲什麼我們有這兩種類型。我必須檢查。在這種情況下你有類似的輸出嗎?你爲什麼更新我的答案?我把從SchemaFactoryWrapper接收到的模式。 –

+0

然後這是一個巨大的錯誤!:JSON模式標準指定一個屬性可以有多個**類型,但不是這樣!這是正確的:*「type」:[「number」,「integer」] *。 在同一個JSON中有兩個鍵是違背每個標準的!鑰匙是獨特的。欲瞭解更多信息,請訪問:http://www.jsonschema.net/ – thermz

6

看一看JSONschema4-mapper項目。隨着以下設置:

SchemaMapper schemaMapper = new SchemaMapper(); 
JSONObject jsonObject = schemaMapper.toJsonSchema4(Entity.class, true); 
System.out.println(jsonObject.toString(4)); 

你得到以下JSON模式在米哈爾Ziober的answer to this question提到的類:

{ 
    "$schema": "http://json-schema.org/draft-04/schema#", 
    "additionalProperties": false, 
    "type": "object", 
    "definitions": { 
     "Profile": { 
      "additionalProperties": false, 
      "type": "object", 
      "properties": { 
       "name": {"type": "string"}, 
       "value": {"type": "string"} 
      } 
     }, 
     "long": { 
      "maximum": 9223372036854775807, 
      "type": "integer", 
      "minimum": -9223372036854775808 
     } 
    }, 
    "properties": { 
     "profiles": { 
      "type": "array", 
      "items": {"$ref": "#/definitions/Profile"} 
     }, 
     "id": {"$ref": "#/definitions/long"} 
    } 
} 
+0

偉大的庫,只是希望我能用JDK 7而不是8作爲基準。如果我們轉向JDK8,請牢記這一點。 – Joe