Skip to content

Commit

Permalink
Merge extension (#10)
Browse files Browse the repository at this point in the history
* Generate JSON schema from type and merge in extension schema

* Rename Extension class
  • Loading branch information
vudodov committed Jul 17, 2019
1 parent 80cdb4f commit 56ecf8e
Show file tree
Hide file tree
Showing 2 changed files with 101 additions and 0 deletions.
71 changes: 71 additions & 0 deletions V.Udodov.Json.Tests/JsonSchemaTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
using Xunit;

namespace V.Udodov.Json.Tests
{
public class JsonSchemaTests
{
private class TheMock
{
public string MockProp { get; set; }
}

[Fact]
public void WhenGeneratingJsonSchemaFromTypeAndStringItShouldGenerate()
{
const string schema = @"{
'type': 'object',
'properties': {
'shoe_size': { 'type': 'number', 'minimum': 5, 'maximum': 12, 'multipleOf': 1.0 }
}
}";

var result = typeof(TheMock).Merge(schema);

result.JsonEquals(@"{
""$id"": ""V.Udodov.Json.Tests.JsonSchemaTests+TheMock"",
""type"": ""object"",
""properties"": {
""mockProp"": {
""type"": [
""string"",
""null""
]
},
""shoe_size"": {
""type"": ""number"",
""minimum"": 5.0,
""maximum"": 12.0,
""multipleOf"": 1.0
}
},
""required"": [
""mockProp""
]
}");
}

[Fact]
public void WhenGeneratingJsonSchemaFromTypeItShouldGenerate()
{
const string schema = null;

var result = typeof(TheMock).Merge(schema);

result.JsonEquals(@"{
""$id"": ""V.Udodov.Json.Tests.JsonSchemaTests+TheMock"",
""type"": ""object"",
""properties"": {
""mockProp"": {
""type"": [
""string"",
""null""
]
}
},
""required"": [
""mockProp""
]
}");
}
}
}
30 changes: 30 additions & 0 deletions V.Udodov.Json/TypeExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
using System;
using System.Linq;
using Newtonsoft.Json.Schema;
using Newtonsoft.Json.Schema.Generation;
using Newtonsoft.Json.Serialization;

namespace V.Udodov.Json
{
public static class TypeExtensions
{
/// <summary>
/// Generates JSON Schema from the type and merges it with JSON Schema provided in <paramref name="jsonSchema"/>.
/// Optionally resulting JSON Schema Id might be defined. If not Id will be generated based from the <paramref name="mergeIn"/> full name.
/// </summary>
public static string Merge(this Type mergeIn, string jsonSchema, Uri id = null)
{
var schema = new JSchemaGenerator
{
SchemaIdGenerationHandling =
id == null ? SchemaIdGenerationHandling.FullTypeName : SchemaIdGenerationHandling.None,
ContractResolver = new CamelCasePropertyNamesContractResolver()
}.Generate(mergeIn);

if(!string.IsNullOrWhiteSpace(jsonSchema))
JSchema.Parse(jsonSchema).Properties.ToList().ForEach(schema.Properties.Add);

return schema.ToString();
}
}
}

0 comments on commit 56ecf8e

Please sign in to comment.