我正在使用Gson
將java對象序列化/反序列化爲json。我想在UI
中顯示它,並且需要一個模式來更好地描述。這將允許我編輯對象並添加比實際更多的數據。
可以Gson
提供json模式嗎?
其他框架是否有這種能力?從Java類創建JSON模式
10
A
回答
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"
}
}
}
}
}
}
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
相關問題
- 1. 從xml模式創建java類
- 2. 從Java創建JSON
- 3. 從json數據創建java模型
- 4. 如何從JSON創建Mongoose模式
- 5. 生成Java類JSON模式
- 6. 創建使用JSON模式
- 7. 如何解析JSON模式並創建默認json對象或生成java類?
- 8. 從JSON模式表示創建火花數據幀模式
- 9. 基於json對象創建JSON模式
- 10. 從json創建reactjs類
- 11. 從形式創建JSON
- 12. 創建xsd模式創建類
- 13. 從本體創建Java類
- 14. 從創建一個Java類
- 15. 從WSDL創建Java類
- 16. 如何創建JSON格式的Java
- 17. 使用json模式創建bigquery表的Java代碼
- 18. 如何創建json模型類?
- 19. 創建從JSON
- 20. 創建從JSON
- 21. 創建從JSON
- 22. 創建JSON模式值依賴關係
- 23. JSON無需創建類(PHP方式)的Java對象
- 24. GSON - 從Java創建JSON樹結構
- 25. 從URL中創建JSON的Java數組
- 26. 從java代碼創建Json文件
- 27. MVC倉庫模式:創建模型類
- 28. 是否有可能在OrientDB中使用JSON模式創建類?
- 29. 創建Java類
- 30. 創建JSON格式
你想什麼UI中顯示?我真的不知道問題是什麼。 'gson'可以將Java-Classes轉換爲JSON格式,這就是'gson'所做的。 – user1983983