GeneratorによるSerializationに一本化するので、ReflectionによるSerializationのJsonSchemaValidatorを削除する。UnitTestを通した。

This commit is contained in:
ousttrue
2020-11-24 17:43:58 +09:00
parent 405253e6f7
commit b44f7c83d4
58 changed files with 120 additions and 7336 deletions

View File

@@ -96,7 +96,7 @@ namespace VRM.Samples
// TODO: Check contents in JSON
/*var newExportedJson = */
JsonParser.Parse(JsonSchema.FromType<glTF>().Serialize(vrm));
// JsonParser.Parse(JsonSchema.FromType<glTF>().Serialize(vrm));
/*
foreach (var kv in importJson.Diff(exportJson))

View File

@@ -126,7 +126,7 @@ namespace UniGLTF
{
return new EnumIntSerialization(t, attr.EnumSerializationType);
}
else if (t == typeof(object))
else if (t == typeof(glTFExtension))
{
return new ExtensionSerialization();
}

View File

@@ -306,9 +306,18 @@ namespace UniGLTF {
continue;
}
var snipet = fi.FieldType.IsClass ? "if(value." + fi.Name + "!=null)" : "";
var snipet = "";
if (fi.FieldType == typeof(string))
{
snipet = $"if(!string.IsNullOrEmpty(value.{fi.Name}))";
}
else if (fi.FieldType.IsClass)
{
snipet = $"if(value.{fi.Name}!=null)";
}
var value = default(string);
if (s_snippets.TryGetValue(path + "/" + fi.Name, out value))
if (s_snippets.TryGetValue($"{path}/{fi.Name}", out value))
{
snipet = value;
}

View File

@@ -219,13 +219,6 @@ namespace UniGLTF
var json = model.ToJson();
Assert.AreEqual(@"{""name"":""mesh"",""primitives"":[{""mode"":0,""indices"":-1,""attributes"":{""POSITION"":0},""material"":0}]}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTFMesh>().Serialize(model, c);
Assert.AreEqual(@"{""name"":""mesh"",""primitives"":[{""mode"":0,""attributes"":{""POSITION"":0},""material"":0}]}", json2);
}
[Test]
@@ -243,13 +236,6 @@ namespace UniGLTF
var json = model.ToJson();
Assert.AreEqual(@"{""mode"":0,""indices"":-1,""attributes"":{""POSITION"":0},""material"":0,""extras"":{""targetNames"":[""aaa""]}}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTFPrimitives>().Serialize(model, c);
Assert.AreEqual(@"{""mode"":0,""attributes"":{""POSITION"":0},""material"":0,""extras"":{""targetNames"":[""aaa""]}}", json2);
}
[Test]
@@ -263,13 +249,6 @@ namespace UniGLTF
var json = model.ToJson();
Assert.AreEqual(@"{""POSITION"":0}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTFAttributes>().Serialize(model, c);
Assert.AreEqual(json, json2);
}
[Test]
@@ -283,28 +262,12 @@ namespace UniGLTF
var json = model.ToJson();
Assert.AreEqual(@"{""index"":1,""texCoord"":0}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTFMaterialBaseColorTextureInfo>().Serialize(model, c);
Assert.AreEqual(json, json2);
}
[Test]
public void TextureInfoTestError()
{
var model = new glTFMaterialBaseColorTextureInfo();
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTFMaterialBaseColorTextureInfo>().Serialize(model, c)
);
Assert.AreEqual("[index.String] minimum: ! -1>=0", ex.Message);
}
[Test]
@@ -319,13 +282,6 @@ namespace UniGLTF
var json = model.ToJson();
Assert.AreEqual(@"{""name"":""a"",""pbrMetallicRoughness"":{""baseColorFactor"":[1,1,1,1],""metallicFactor"":1,""roughnessFactor"":1},""emissiveFactor"":[0.5,0.5,0.5],""doubleSided"":false}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTFMaterial>().Serialize(model, c);
Assert.AreEqual(@"{""name"":""a"",""pbrMetallicRoughness"":{""baseColorFactor"":[1,1,1,1],""metallicFactor"":1,""roughnessFactor"":1},""emissiveFactor"":[0.5,0.5,0.5],""doubleSided"":false}", json2);
}
[Test]
@@ -337,13 +293,6 @@ namespace UniGLTF
emissiveFactor = new float[] { 0.5f, 0.5f, 0.5f },
alphaMode = "MASK",
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json = JsonSchema.FromType<glTFMaterial>().Serialize(model, c);
Assert.AreEqual(@"{""name"":""a"",""pbrMetallicRoughness"":{""baseColorFactor"":[1,1,1,1],""metallicFactor"":1,""roughnessFactor"":1},""emissiveFactor"":[0.5,0.5,0.5],""alphaMode"":""MASK"",""alphaCutoff"":0.5,""doubleSided"":false}", json);
}
[Test]
@@ -430,15 +379,6 @@ namespace UniGLTF
name = "b",
emissiveFactor = new float[] { 1.5f, 0.5f, 0.5f },
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTFMaterial>().Serialize(model, c)
);
Assert.AreEqual("[emissiveFactor.String] maximum: ! 1.5<=1", ex.Message);
}
[Test]
@@ -454,13 +394,6 @@ namespace UniGLTF
var json = model.ToJson();
Assert.AreEqual(@"{""name"":""a"",""skin"":0}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTFNode>().Serialize(model, c);
Assert.AreEqual(@"{""name"":""a"",""extras"":{}}", json2);
}
[Test]
@@ -473,13 +406,6 @@ namespace UniGLTF
skin = 0,
camera = -1,
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json = JsonSchema.FromType<glTFNode>().Serialize(model, c);
Assert.AreEqual(@"{""name"":""a"",""mesh"":2,""skin"":0,""extras"":{}}", json);
}
[Test]
@@ -490,15 +416,6 @@ namespace UniGLTF
name = "a",
camera = -2,
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTFNode>().Serialize(model, c)
);
Assert.AreEqual("[camera.String] minimum: ! -2>=0", ex.Message);
}
[Test]
@@ -511,15 +428,8 @@ namespace UniGLTF
};
var json = model.ToJson();
Assert.AreEqual(@"{""inverseBindMatrices"":-1,""joints"":[1]}", json);
Assert.AreEqual(@"{""inverseBindMatrices"":-1,""joints"":[1],""name"":""b""}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTFSkin>().Serialize(model, c);
Assert.AreEqual(@"{""joints"":[1],""name"":""b""}", json2);
}
[Test]
@@ -535,13 +445,6 @@ namespace UniGLTF
// "name" = "", not excluded
Assert.AreEqual(@"{""inverseBindMatrices"":-1,""joints"":[1]}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTFSkin>().Serialize(model, c);
Assert.AreEqual(@"{""joints"":[1],""name"":""""}", json2);
}
[Test]
@@ -552,15 +455,6 @@ namespace UniGLTF
name = "b",
joints = null,
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTFSkin>().Serialize(model, c)
);
Assert.AreEqual("[joints.String] null", ex.Message);
}
[Test]
@@ -571,15 +465,6 @@ namespace UniGLTF
name = "b",
joints = new int[] { },
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTFSkin>().Serialize(model, c)
);
Assert.AreEqual("[joints.String] minItems", ex.Message);
}
[Test]
@@ -593,13 +478,6 @@ namespace UniGLTF
//var json = model.ToJson();
//Assert.AreEqual(@"{""inverseBindMatrices"":-1,""joints"":[1]}", json);
//Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTFAssets>().Serialize(model, c);
Assert.AreEqual(@"{""version"":""0.49""}", json2);
}
[Test]
@@ -610,15 +488,6 @@ namespace UniGLTF
//var json = model.ToJson();
//Assert.AreEqual(@"{""inverseBindMatrices"":-1,""joints"":[1]}", json);
//Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTFAssets>().Serialize(model, c)
);
Assert.AreEqual("[version.String] null", ex.Message);
}
[Test]
@@ -630,15 +499,7 @@ namespace UniGLTF
{
version = "0.49",
},
extensions = null,
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF>().Serialize(model, c);
Assert.AreEqual(@"{""asset"":{""version"":""0.49""},""extras"":{}}", json2);
}
[Test]
@@ -758,13 +619,5 @@ namespace UniGLTF
Assert.NotNull(dummy.Value);
Assert.False(dummy.Value.Value);
}
[Test]
public void UniJSONTest()
{
var dummy = default(Dummy);
"{}".ParseAsJson().Deserialize(ref dummy);
Assert.Null(dummy.Value);
}
}
}

View File

@@ -11,6 +11,8 @@ namespace UniGLTF
public static readonly Utf8String ExtensionNameUtf8 = Utf8String.From(ExtensionName);
static readonly byte[] Raw = new byte[] { (byte)'{', (byte)'}' };
public static glTFMaterial CreateDefault()
{
return new glTFMaterial
@@ -21,7 +23,7 @@ namespace UniGLTF
roughnessFactor = 0.9f,
metallicFactor = 0.0f,
},
extensions = glTFExtension.Create(ExtensionName, "{}")
extensions = glTFExtension.Create(ExtensionName, new ArraySegment<byte>(Raw))
};
}
@@ -45,7 +47,7 @@ namespace UniGLTF
public static glTFExtension Serialize()
{
return glTFExtension.Create(ExtensionName, "{}");
return glTFExtension.Create(ExtensionName, new ArraySegment<byte>(Raw));
}
}
}

View File

@@ -19,10 +19,10 @@ namespace UniGLTF
{
Serialized = new Dictionary<string, ArraySegment<byte>>();
}
public static glTFExtension Create(string key, string serialized)
public static glTFExtension Create(string key, ArraySegment<byte> raw)
{
var e = new glTFExtension();
e.Serialized.Add(key, new ArraySegment<byte>(Utf8.GetBytes(serialized)));
e.Serialized.Add(key, raw);
return e;
}
#endregion
@@ -74,10 +74,13 @@ namespace UniGLTF
{
//CommaCheck();
f.BeginMap();
foreach (var kv in v.Serialized)
if (v.Serialized != null)
{
f.Key(kv.Key);
f.Raw(kv.Value);
foreach (var kv in v.Serialized)
{
f.Key(kv.Key);
f.Raw(kv.Value);
}
}
f.EndMap();
}

View File

@@ -73,7 +73,7 @@ namespace UniGLTF
}
f.EndList();
return glTFExtension.Create(ExtraName, f.GetStore().ToString());
return glTFExtension.Create(ExtraName, f.GetStore().Bytes);
}
public static void Serialize(glTFMesh gltfMesh, IEnumerable<string> targetNames)

View File

@@ -119,22 +119,22 @@ namespace UniGLTF {
{
f.BeginMap(0); // dummy
if(value.generator!=null)
if(!string.IsNullOrEmpty(value.generator))
{
f.Key("generator"); f.GenSerialize(value.generator);
}
if(value.version!=null)
if(!string.IsNullOrEmpty(value.version))
{
f.Key("version"); f.GenSerialize(value.version);
}
if(value.copyright!=null)
if(!string.IsNullOrEmpty(value.copyright))
{
f.Key("copyright"); f.GenSerialize(value.copyright);
}
if(value.minVersion!=null)
if(!string.IsNullOrEmpty(value.minVersion))
{
f.Key("minVersion"); f.GenSerialize(value.minVersion);
}
@@ -173,7 +173,7 @@ namespace UniGLTF {
{
f.BeginMap(0); // dummy
if(value.uri!=null)
if(!string.IsNullOrEmpty(value.uri))
{
f.Key("uri"); f.GenSerialize(value.uri);
}
@@ -193,7 +193,7 @@ namespace UniGLTF {
f.Key("extras"); f.GenSerialize(value.extras);
}
if(value.name!=null)
if(!string.IsNullOrEmpty(value.name))
{
f.Key("name"); f.GenSerialize(value.name);
}
@@ -252,7 +252,7 @@ namespace UniGLTF {
f.Key("extras"); f.GenSerialize(value.extras);
}
if(value.name!=null)
if(!string.IsNullOrEmpty(value.name))
{
f.Key("name"); f.GenSerialize(value.name);
}
@@ -291,7 +291,7 @@ namespace UniGLTF {
f.Key("byteOffset"); f.GenSerialize(value.byteOffset);
}
if(value.type!=null)
if(!string.IsNullOrEmpty(value.type))
{
f.Key("type"); f.GenSerialize(value.type);
}
@@ -326,7 +326,7 @@ namespace UniGLTF {
f.Key("sparse"); f.GenSerialize(value.sparse);
}
if(value.name!=null)
if(!string.IsNullOrEmpty(value.name))
{
f.Key("name"); f.GenSerialize(value.name);
}
@@ -500,7 +500,7 @@ namespace UniGLTF {
f.Key("extras"); f.GenSerialize(value.extras);
}
if(value.name!=null)
if(!string.IsNullOrEmpty(value.name))
{
f.Key("name"); f.GenSerialize(value.name);
}
@@ -554,7 +554,7 @@ namespace UniGLTF {
f.Key("extras"); f.GenSerialize(value.extras);
}
if(value.name!=null)
if(!string.IsNullOrEmpty(value.name))
{
f.Key("name"); f.GenSerialize(value.name);
}
@@ -588,12 +588,12 @@ namespace UniGLTF {
{
f.BeginMap(0); // dummy
if(value.name!=null)
if(!string.IsNullOrEmpty(value.name))
{
f.Key("name"); f.GenSerialize(value.name);
}
if(value.uri!=null)
if(!string.IsNullOrEmpty(value.uri))
{
f.Key("uri"); f.GenSerialize(value.uri);
}
@@ -603,7 +603,7 @@ namespace UniGLTF {
f.Key("bufferView"); f.GenSerialize(value.bufferView);
}
if(value.mimeType!=null)
if(!string.IsNullOrEmpty(value.mimeType))
{
f.Key("mimeType"); f.GenSerialize(value.mimeType);
}
@@ -637,7 +637,7 @@ namespace UniGLTF {
{
f.BeginMap(0); // dummy
if(value.name!=null)
if(!string.IsNullOrEmpty(value.name))
{
f.Key("name"); f.GenSerialize(value.name);
}
@@ -667,7 +667,7 @@ namespace UniGLTF {
f.Key("emissiveFactor"); f.GenSerialize(value.emissiveFactor);
}
if(value.alphaMode!=null)
if(!string.IsNullOrEmpty(value.alphaMode))
{
f.Key("alphaMode"); f.GenSerialize(value.alphaMode);
}
@@ -904,7 +904,7 @@ namespace UniGLTF {
{
f.BeginMap(0); // dummy
if(value.name!=null)
if(!string.IsNullOrEmpty(value.name))
{
f.Key("name"); f.GenSerialize(value.name);
}
@@ -1084,7 +1084,7 @@ namespace UniGLTF {
{
f.BeginMap(0); // dummy
if(value.name!=null)
if(!string.IsNullOrEmpty(value.name))
{
f.Key("name"); f.GenSerialize(value.name);
}
@@ -1199,7 +1199,7 @@ namespace UniGLTF {
f.Key("extras"); f.GenSerialize(value.extras);
}
if(value.name!=null)
if(!string.IsNullOrEmpty(value.name))
{
f.Key("name"); f.GenSerialize(value.name);
}
@@ -1238,7 +1238,7 @@ namespace UniGLTF {
f.Key("extras"); f.GenSerialize(value.extras);
}
if(value.name!=null)
if(!string.IsNullOrEmpty(value.name))
{
f.Key("name"); f.GenSerialize(value.name);
}
@@ -1262,7 +1262,7 @@ namespace UniGLTF {
{
f.BeginMap(0); // dummy
if(value.name!=null)
if(!string.IsNullOrEmpty(value.name))
{
f.Key("name"); f.GenSerialize(value.name);
}
@@ -1339,7 +1339,7 @@ namespace UniGLTF {
f.Key("node"); f.GenSerialize(value.node);
}
if(value.path!=null)
if(!string.IsNullOrEmpty(value.path))
{
f.Key("path"); f.GenSerialize(value.path);
}
@@ -1378,7 +1378,7 @@ namespace UniGLTF {
f.Key("input"); f.GenSerialize(value.input);
}
if(value.interpolation!=null)
if(!string.IsNullOrEmpty(value.interpolation))
{
f.Key("interpolation"); f.GenSerialize(value.interpolation);
}
@@ -1432,7 +1432,7 @@ namespace UniGLTF {
f.Key("type"); f.GenSerialize(value.type);
}
if(value.name!=null)
if(!string.IsNullOrEmpty(value.name))
{
f.Key("name"); f.GenSerialize(value.name);
}

View File

@@ -344,28 +344,28 @@ namespace UniGLTF
}
}
}
for (int i = 0; i < GLTF.meshes.Count; ++i)
{
var mesh = GLTF.meshes[i];
try
{
for (int j = 0; j < mesh.primitives.Count; ++j)
{
var primitive = mesh.primitives[j];
for (int k = 0; k < primitive.targets.Count; ++k)
{
var extraName = parsed["meshes"][i]["primitives"][j]["targets"][k]["extra"]["name"].Value.GetString();
//Debug.LogFormat("restore morphName: {0}", extraName);
throw new NotImplementedException();
// primitive.extras.targetNames.Add(extraName);
}
}
}
catch (Exception)
{
// do nothing
}
}
// for (int i = 0; i < GLTF.meshes.Count; ++i)
// {
// var mesh = GLTF.meshes[i];
// try
// {
// for (int j = 0; j < mesh.primitives.Count; ++j)
// {
// var primitive = mesh.primitives[j];
// for (int k = 0; k < primitive.targets.Count; ++k)
// {
// var extraName = parsed["meshes"][i]["primitives"][j]["targets"][k]["extra"]["name"].Value.GetString();
// //Debug.LogFormat("restore morphName: {0}", extraName);
// throw new NotImplementedException();
// // primitive.extras.targetNames.Add(extraName);
// }
// }
// }
// catch (Exception)
// {
// // do nothing
// }
// }
#if false
for (int i = 0; i < GLTF.nodes.Count; ++i)
{

View File

@@ -79,13 +79,13 @@ namespace UniJSON
new Dictionary<string, object>{
} } }, "{\"a\":{}}");
SerializeValue(new Point { X = 1 }, "{\"X\":1,\"Y\":0}");
// SerializeValue(new Point { X = 1 }, "{\"X\":1,\"Y\":0}");
SerializeValue(HogeFuga.Fuga, "1");
// SerializeValue(HogeFuga.Fuga, "1");
SerializeValue(new EnumTest(), "{\"EnumDefault\":0,\"EnumAsInt\":0,\"EnumAsString\":\"Hoge\",\"EnumAsLowerString\":\"hoge\"}");
// SerializeValue(new EnumTest(), "{\"EnumDefault\":0,\"EnumAsInt\":0,\"EnumAsString\":\"Hoge\",\"EnumAsLowerString\":\"hoge\"}");
SerializeValue((object)new Point { X = 1 }, "{\"X\":1,\"Y\":0}");
// SerializeValue((object)new Point { X = 1 }, "{\"X\":1,\"Y\":0}");
}
[Test]
@@ -111,40 +111,40 @@ namespace UniJSON
#endregion
#region Deserialize
static void DeserializeValue<T>(T value, string json)
{
var parsed = JsonParser.Parse(json);
// static void DeserializeValue<T>(T value, string json)
// {
// var parsed = JsonParser.Parse(json);
var t = default(T);
parsed.Deserialize(ref t);
// var t = default(T);
// parsed.Deserialize(ref t);
Assert.AreEqual(value, t);
}
// Assert.AreEqual(value, t);
// }
[Test]
public void JsonDeserializerTest()
{
DeserializeValue(1, "1");
DeserializeValue(1.1f, "1.1");
DeserializeValue(1.2, "1.2");
DeserializeValue(true, "true");
DeserializeValue(false, "false");
DeserializeValue("ascii", "\"ascii\"");
// [Test]
// public void JsonDeserializerTest()
// {
// DeserializeValue(1, "1");
// DeserializeValue(1.1f, "1.1");
// DeserializeValue(1.2, "1.2");
// DeserializeValue(true, "true");
// DeserializeValue(false, "false");
// DeserializeValue("ascii", "\"ascii\"");
DeserializeValue(new[] { 1 }, "[1]");
DeserializeValue(new[] { 1.1f }, "[1.1]");
DeserializeValue(new[] { 1.2 }, "[1.2]");
DeserializeValue(new[] { true, false }, "[true,false]");
DeserializeValue(new[] { "ascii" }, "[\"ascii\"]");
DeserializeValue(new List<int> { 1 }, "[1]");
//DeserializeValue(new object[] { null, 1, "a" }, "[null,1,\"a\"]");
// DeserializeValue(new[] { 1 }, "[1]");
// DeserializeValue(new[] { 1.1f }, "[1.1]");
// DeserializeValue(new[] { 1.2 }, "[1.2]");
// DeserializeValue(new[] { true, false }, "[true,false]");
// DeserializeValue(new[] { "ascii" }, "[\"ascii\"]");
// DeserializeValue(new List<int> { 1 }, "[1]");
// //DeserializeValue(new object[] { null, 1, "a" }, "[null,1,\"a\"]");
DeserializeValue(new Point { X = 1 }, "{\"X\":1,\"Y\":0}");
// DeserializeValue(new Point { X = 1 }, "{\"X\":1,\"Y\":0}");
DeserializeValue(HogeFuga.Fuga, "1");
// DeserializeValue(HogeFuga.Fuga, "1");
DeserializeValue(new EnumTest(), "{\"EnumDefault\":0,\"EnumAsInt\":0,\"EnumAsString\":\"Hoge\",\"EnumAsLowerString\":\"hoge\"}");
}
// DeserializeValue(new EnumTest(), "{\"EnumDefault\":0,\"EnumAsInt\":0,\"EnumAsString\":\"Hoge\",\"EnumAsLowerString\":\"hoge\"}");
// }
class DictionaryValue: IEquatable<DictionaryValue>
{
@@ -185,18 +185,18 @@ namespace UniJSON
}
}
[Test]
public void JsonDictionaryDeserializerTest()
{
DeserializeValue(new Dictionary<string, object> { }, "{}");
DeserializeValue(new Dictionary<string, object> { { "a", 1 } }, "{\"a\":1}");
DeserializeValue(new Dictionary<string, object> { { "a",
new Dictionary<string, object>{
} } }, "{\"a\":{}}");
// [Test]
// public void JsonDictionaryDeserializerTest()
// {
// DeserializeValue(new Dictionary<string, object> { }, "{}");
// DeserializeValue(new Dictionary<string, object> { { "a", 1 } }, "{\"a\":1}");
// DeserializeValue(new Dictionary<string, object> { { "a",
// new Dictionary<string, object>{
// } } }, "{\"a\":{}}");
// fix dictionary member deserialization
DeserializeValue(new DictionaryValue(), "{\"Dict\": {}}");
}
// // fix dictionary member deserialization
// DeserializeValue(new DictionaryValue(), "{\"Dict\": {}}");
// }
#endregion
}
}

View File

@@ -1,150 +0,0 @@
#pragma warning disable 0649
using NUnit.Framework;
namespace UniJSON
{
public class SchemaTests
{
/// <summary>
/// http://json-schema.org/examples.html
/// </summary>
[JsonSchema(Title="Person")]
public class Person
{
[JsonSchema(Required = true)]
public string firstName;
[JsonSchema(Required = true)]
public string lastName;
[JsonSchema(Description = "Age in years", Minimum = 0)]
public int age;
}
[Test]
public void CreateFromClass()
{
var s = JsonSchema.FromType<Person>();
Assert.AreEqual("Person", s.Title);
var v = s.Validator as JsonObjectValidator;
Assert.AreEqual("Age in years", v.Properties["age"].Description);
Assert.AreEqual(new[] { "firstName", "lastName" }, v.Required);
var f = new JsonFormatter(2);
s.ToJson(f);
var json = f.ToString();
var parsed = JsonParser.Parse(json);
Assert.AreEqual(0, parsed["properties"]["age"]["minimum"].GetInt32());
}
[JsonSchema(Title="MultipleConstraints")]
public class MultipleConstraints
{
[JsonSchema(Required = true, Minimum = 0, Maximum = 100)]
public int ranged;
}
[Test]
public void CreateFromClassWithMultipleConstraints()
{
var s = JsonSchema.FromType<MultipleConstraints>();
var v = s.Validator as JsonObjectValidator;
var rangedV = v.Properties["ranged"].Validator as JsonIntValidator;
Assert.AreEqual(0, rangedV.Minimum);
Assert.AreEqual(100, rangedV.Maximum);
}
public enum ProjectionType
{
Perspective,
Orthographic
}
class EnumStringTest
{
[JsonSchema(EnumSerializationType = EnumSerializationType.AsLowerString)]
public ProjectionType type;
}
class EnumIntTest
{
[JsonSchema(EnumSerializationType = EnumSerializationType.AsInt)]
public ProjectionType type;
}
[Test]
public void TestEnumAsString()
{
var json = @"
{
""type"": ""object"",
""properties"": {
""type"": {
""anyOf"": [
{
""enum"": [ ""perspective"" ]
},
{
""enum"": [ ""orthographic"" ]
},
{
""type"": ""string""
}
]
}
}
}
";
var fromJson = new JsonSchema();
fromJson.Parse(null, JsonParser.Parse(json), "enum test");
var fromType = JsonSchema.FromType<EnumStringTest>();
Assert.AreEqual(fromJson, fromType);
}
[Test]
public void TestEnumAsInt()
{
var json = @"
{
""type"": ""object"",
""properties"": {
""type"": {
""anyOf"": [
{
""enum"": [ 0 ]
},
{
""enum"": [ 1 ]
},
{
""type"": ""integer""
}
]
}
}
}
";
var fromJson = new JsonSchema();
fromJson.Parse(null, JsonParser.Parse(json), "enum test");
var fromType = JsonSchema.FromType<EnumIntTest>();
Assert.AreEqual(fromJson, fromType);
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: d4dfd16b1b05c8640898b955df61c51b
timeCreated: 1526055801
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,200 +0,0 @@
using NUnit.Framework;
namespace UniJSON
{
public class SerializeWithSchemaTests
{
[JsonSchema(Title="CheckConstraintsTest")]
public class CheckConstraintsTest
{
[JsonSchema(Minimum = 0)]
public int X;
[JsonSchema(Minimum = 10, ExplicitIgnorableValue = 0)] // Not required, thus ignored when the value violates the constraints
public int Y;
}
[Test]
public void TestCheckConstraints()
{
var obj = new CheckConstraintsTest()
{
X = 0,
Y = 0, // Will be excluded because 0 doesn't satisfy a requirement of "Minimum = 10"
};
var s = JsonSchema.FromType<CheckConstraintsTest>();
{
var c = new JsonSchemaValidationContext(obj);
Assert.Null(s.Validator.Validate(c, s));
}
var actual = s.Serialize(obj);
var expected = @"{""X"":0}";
Assert.AreEqual(expected, actual);
}
[JsonSchema(Title="ObjectNestedTest")]
public class ObjectNestedTest
{
public CheckConstraintsTest C;
}
[Test]
public void TestObjectNested()
{
var obj = new ObjectNestedTest()
{
C = new CheckConstraintsTest(),
};
var s = JsonSchema.FromType<ObjectNestedTest>();
{
var c = new JsonSchemaValidationContext(obj);
Assert.Null(s.Validator.Validate(c, s));
}
var actual = s.Serialize(obj);
var expected = @"{""C"":{""X"":0}}";
Assert.AreEqual(expected, actual);
}
[Test]
public void TestObjectNestedWithNull()
{
var obj = new ObjectNestedTest();
var s = JsonSchema.FromType<ObjectNestedTest>();
{
var c = new JsonSchemaValidationContext(obj);
Assert.Null(s.Validator.Validate(c, s));
}
var actual = s.Serialize(obj);
var expected = @"{}";
Assert.AreEqual(expected, actual);
}
public class HasDepsTest
{
[JsonSchema(Minimum = 0, ExplicitIgnorableValue = -1)]
public int X;
[JsonSchema(Dependencies = new string[] {"X"})]
public int Y;
}
[Test]
public void TestHasDeps()
{
var obj = new HasDepsTest();
var s = JsonSchema.FromType<HasDepsTest>();
{
var c = new JsonSchemaValidationContext(obj);
Assert.Null(s.Validator.Validate(c, s));
}
var actual = s.Serialize(obj);
var expected = @"{""X"":0,""Y"":0}";
Assert.AreEqual(expected, actual);
}
[Test]
public void TestHasDepsHasViolation()
{
var obj = new HasDepsTest()
{
X = -1,
};
var s = JsonSchema.FromType<HasDepsTest>();
{
var c = new JsonSchemaValidationContext(obj);
Assert.Null(s.Validator.Validate(c, s));
}
var actual = s.Serialize(obj);
var expected = @"{}";
Assert.AreEqual(expected, actual);
}
public class HasStringTest
{
public string X;
}
[Test]
public void TestHasString()
{
var obj = new HasStringTest()
{
X = "a",
};
var s = JsonSchema.FromType<HasStringTest>();
{
var c = new JsonSchemaValidationContext(obj);
Assert.Null(s.Validator.Validate(c, s));
}
var actual = s.Serialize(obj);
var expected = @"{""X"":""a""}";
Assert.AreEqual(expected, actual);
}
[Test]
public void TestHasStringWithNull()
{
var obj = new HasStringTest();
var s = JsonSchema.FromType<HasStringTest>();
{
var c = new JsonSchemaValidationContext(obj);
Assert.Null(s.Validator.Validate(c, s));
}
var actual = s.Serialize(obj);
var expected = @"{}";
Assert.AreEqual(expected, actual);
}
public class NestedRequiredTestParent
{
[JsonSchema(Required = true)]
public NestedRequiredTestChild C;
}
public class NestedRequiredTestChild
{
public string X;
}
[Test]
public void TestNestedRequired()
{
var obj = new NestedRequiredTestParent()
{
C = new NestedRequiredTestChild(),
};
var s = JsonSchema.FromType<NestedRequiredTestParent>();
{
var c = new JsonSchemaValidationContext(obj);
Assert.Null(s.Validator.Validate(c, s));
}
var actual = s.Serialize(obj);
var expected = @"{""C"":{}}";
Assert.AreEqual(expected, actual);
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: f1d1c3d9d4d20db409e9d5d9d671abbe
timeCreated: 1546930461
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,441 +0,0 @@
using NUnit.Framework;
using System.Collections.Generic;
namespace UniJSON
{
public class ValidatorTests
{
[Test]
public void IntValidator()
{
var c = new JsonSchemaValidationContext("test");
{
var v = new JsonIntValidator();
v.Maximum = 0;
Assert.NotNull(v.Validate(c, 1));
Assert.Null(v.Validate(c, 0));
Assert.Null(v.Validate(c, -1));
}
{
var v = new JsonIntValidator();
v.Maximum = 0;
v.ExclusiveMaximum = true;
Assert.NotNull(v.Validate(c, 1));
Assert.NotNull(v.Validate(c, 0));
Assert.Null(v.Validate(c, -1));
}
{
var v = new JsonIntValidator();
v.Minimum = 0;
Assert.Null(v.Validate(c, 1));
Assert.Null(v.Validate(c, 0));
Assert.NotNull(v.Validate(c, -1));
}
{
var v = new JsonIntValidator();
v.Minimum = 0;
v.ExclusiveMinimum = true;
Assert.Null(v.Validate(c, 1));
Assert.NotNull(v.Validate(c, 0));
Assert.NotNull(v.Validate(c, -1));
}
{
var v = new JsonIntValidator();
v.MultipleOf = 4;
Assert.Null(v.Validate(c, 4));
Assert.NotNull(v.Validate(c, 5));
}
Assert.True(c.IsEmpty());
}
[Test]
public void NumberValidator()
{
var c = new JsonSchemaValidationContext("test");
{
var v = new JsonNumberValidator();
v.Maximum = 0.1;
Assert.NotNull(v.Validate(c, 1));
Assert.Null(v.Validate(c, 0.1));
Assert.Null(v.Validate(c, -1));
}
{
var v = new JsonNumberValidator();
v.Maximum = 0.1;
v.ExclusiveMaximum = true;
Assert.NotNull(v.Validate(c, 1));
Assert.NotNull(v.Validate(c, 0.1));
Assert.Null(v.Validate(c, -1));
}
{
var v = new JsonNumberValidator();
v.Minimum = 0.1;
Assert.Null(v.Validate(c, 1));
Assert.Null(v.Validate(c, 0.1));
Assert.NotNull(v.Validate(c, -1));
}
{
var v = new JsonNumberValidator();
v.Minimum = 0.1;
v.ExclusiveMinimum = true;
Assert.Null(v.Validate(c, 1));
Assert.NotNull(v.Validate(c, 0.1));
Assert.NotNull(v.Validate(c, -1));
}
Assert.True(c.IsEmpty());
}
[Test]
public void BoolValidator()
{
// ???
}
[Test]
public void StringValidator()
{
var c = new JsonSchemaValidationContext("test");
{
var v = new JsonStringValidator();
Assert.Null(v.Validate(c, ""));
Assert.Null(v.Validate(c, "a"));
}
{
var v = new JsonStringValidator();
v.MinLength = 1;
Assert.Null(v.Validate(c, "a"));
Assert.NotNull(v.Validate(c, ""));
}
{
var v = new JsonStringValidator();
v.MaxLength = 1;
Assert.Null(v.Validate(c, "a"));
Assert.NotNull(v.Validate(c, "ab"));
}
{
var v = new JsonStringValidator();
v.Pattern = new System.Text.RegularExpressions.Regex("abc");
Assert.Null(v.Validate(c, "abc"));
Assert.NotNull(v.Validate(c, "ab"));
}
{
var v = new JsonStringValidator();
v.Pattern = new System.Text.RegularExpressions.Regex("ab+");
Assert.Null(v.Validate(c, "abb"));
Assert.Null(v.Validate(c, "ab"));
Assert.NotNull(v.Validate(c, "a"));
}
Assert.True(c.IsEmpty());
}
[Test]
public void StringEnumValidator()
{
var c = new JsonSchemaValidationContext("test");
{
var v = JsonStringEnumValidator.Create(new string[] { "a", "b" }, EnumSerializationType.AsString);
Assert.Null(v.Validate(c, "a"));
Assert.NotNull(v.Validate(c, "c"));
}
Assert.True(c.IsEmpty());
}
[Test]
public void IntEnumValidator()
{
var c = new JsonSchemaValidationContext("test");
{
var v = new JsonIntEnumValidator();
v.Values = new int[] { 1, 2 };
Assert.Null(v.Validate(c, 1));
Assert.NotNull(v.Validate(c, 3));
}
Assert.True(c.IsEmpty());
}
[Test]
public void ArrayValidator()
{
var c = new JsonSchemaValidationContext("test");
{
var v = new JsonArrayValidator();
v.MaxItems = 1;
Assert.Null(v.Validate(c, new object[] { 0 }));
Assert.NotNull(v.Validate(c, new object[] { 0, 1 }));
}
{
var v = new JsonArrayValidator();
v.MinItems = 1;
Assert.Null(v.Validate(c, new object[] { 0 }));
Assert.NotNull(v.Validate(c, new object[] { }));
}
Assert.True(c.IsEmpty());
}
class Hoge
{
[JsonSchema(Required = true, Minimum = 1)]
public int Value;
}
[Test]
public void ObjectValidator()
{
var c = new JsonSchemaValidationContext("test");
{
var s = JsonSchema.FromType<Hoge>();
Assert.Null(s.Validator.Validate(c, new Hoge { Value = 1 }));
Assert.NotNull(s.Validator.Validate(c, new Hoge { Value = 0 }));
}
Assert.True(c.IsEmpty());
}
class NotRequired
{
[JsonSchema(Minimum = 1)]
public int Value;
}
[Test]
public void ObjectValidatorForNotRequired()
{
{
var c = new JsonSchemaValidationContext("test")
{
EnableDiagnosisForNotRequiredFields = false, // Default behaviour
};
var s = JsonSchema.FromType<NotRequired>();
// An error is not returned because Value is not 'Required' and the diagnosis is not enabled
Assert.Null(s.Validator.Validate(c, new NotRequired { Value = 0 }));
Assert.True(c.IsEmpty());
}
{
var c = new JsonSchemaValidationContext("test")
{
EnableDiagnosisForNotRequiredFields = true,
};
var s = JsonSchema.FromType<NotRequired>();
Assert.NotNull(s.Validator.Validate(c, new NotRequired { Value = 0 }));
Assert.True(c.IsEmpty());
}
}
class NotRequiredWithIgnorable
{
[JsonSchema(Minimum = 2, ExplicitIgnorableValue = -1)]
public int Value;
}
[Test]
public void ObjectValidatorForNotRequiredWithIgnorable()
{
{
var c = new JsonSchemaValidationContext("test")
{
EnableDiagnosisForNotRequiredFields = false, // Default behaviour
};
var s = JsonSchema.FromType<NotRequiredWithIgnorable>();
// An error is not returned because Value is not 'Required' and the diagnosis is not enabled
Assert.Null(s.Validator.Validate(c, new NotRequiredWithIgnorable { Value = 0 }));
Assert.True(c.IsEmpty());
}
{
var c = new JsonSchemaValidationContext("test")
{
EnableDiagnosisForNotRequiredFields = true,
};
var s = JsonSchema.FromType<NotRequiredWithIgnorable>();
Assert.NotNull(s.Validator.Validate(c, new NotRequiredWithIgnorable { Value = 0 }));
Assert.True(c.IsEmpty());
}
{
var c = new JsonSchemaValidationContext("test")
{
EnableDiagnosisForNotRequiredFields = true,
};
var s = JsonSchema.FromType<NotRequiredWithIgnorable>();
// An error is NOT returned even though diagnosis is enabled because of an ignorable value is matched
Assert.Null(s.Validator.Validate(c, new NotRequiredWithIgnorable { Value = -1 }));
Assert.True(c.IsEmpty());
}
}
[Test]
public void DictionaryValidator()
{
var c = new JsonSchemaValidationContext("test");
{
var s = JsonSchema.FromType<Dictionary<string, int>>();
Assert.True(s.Validator is JsonDictionaryValidator<int>);
var v = s.Validator as JsonDictionaryValidator<int>;
v.MinProperties = 1;
v.AdditionalProperties = JsonSchema.FromType<int>();
(v.AdditionalProperties.Validator as JsonIntValidator).Minimum = 0;
Assert.Null(s.Validator.Validate(c, new Dictionary<string, int>
{
{"POSITION", 0}
}));
var result = s.Validator.Validate(c, new Dictionary<string, int>
{
{"POSITION", -1}
});
Assert.NotNull(result);
}
Assert.True(c.IsEmpty());
}
class HasDictionary
{
public Dictionary<string, float> primitiveProperties = new Dictionary<string, float>();
// TODO: fix
// public Dictionary<string, Nested> nestedProperties = new Dictionary<string, Nested>();
}
[Test]
public void HasDictionaryObjectValidator()
{
var c = new JsonSchemaValidationContext("test");
{
var s = JsonSchema.FromType<HasDictionary>();
Assert.Null(s.Validator.Validate(c, new HasDictionary()));
}
Assert.True(c.IsEmpty());
}
class HasArrayObject
{
[ItemJsonSchema(Minimum = 0.0, Maximum = 1.0)]
public float[] xs;
}
[Test]
public void HasArrayObjectValidator()
{
{
var c = new JsonSchemaValidationContext("test")
{
EnableDiagnosisForNotRequiredFields = true,
};
var s = JsonSchema.FromType<HasArrayObject>();
Assert.Null(s.Validator.Validate(c, new HasArrayObject { xs = new float[] { } }));
Assert.Null(s.Validator.Validate(c, new HasArrayObject { xs = new float[] { 0.5f } }));
Assert.NotNull(s.Validator.Validate(c, new HasArrayObject { xs = new float[] { 1.5f } }));
Assert.True(c.IsEmpty());
}
}
class HasListObject
{
[ItemJsonSchema(Minimum = 0.0, Maximum = 1.0)]
public List<float> xs;
}
[Test]
public void HasListObjectValidator()
{
{
var c = new JsonSchemaValidationContext("test")
{
EnableDiagnosisForNotRequiredFields = true,
};
var s = JsonSchema.FromType<HasListObject>();
Assert.Null(s.Validator.Validate(c, new HasListObject { xs = new List<float> { } }));
Assert.Null(s.Validator.Validate(c, new HasListObject { xs = new List<float> { 0.5f } }));
Assert.NotNull(s.Validator.Validate(c, new HasListObject { xs = new List<float> { 1.5f } }));
Assert.True(c.IsEmpty());
}
}
class HasRequiredListObject
{
[JsonSchema(Required = true, MinItems = 1)]
[ItemJsonSchema(Minimum = 0)]
public int[] xs;
}
[Test]
public void HasRequiredListObjectValidator()
{
{
var c = new JsonSchemaValidationContext("test")
{
EnableDiagnosisForNotRequiredFields = true,
};
var s = JsonSchema.FromType<HasRequiredListObject>();
Assert.NotNull(s.Validator.Validate(c, new HasRequiredListObject()));
Assert.NotNull(s.Validator.Validate(c, new HasRequiredListObject { xs = new int[] {} }));
Assert.NotNull(s.Validator.Validate(c, new HasRequiredListObject { xs = new int[] { -1 } }));
Assert.Null(s.Validator.Validate(c, new HasRequiredListObject { xs = new int[] { 0 } }));
Assert.True(c.IsEmpty());
}
}
class HasRequiredStringObject
{
[JsonSchema(Required = true)]
public string s;
}
[Test]
public void HasRequiredStringObjectValidator()
{
{
var c = new JsonSchemaValidationContext("test")
{
EnableDiagnosisForNotRequiredFields = true,
};
var s = JsonSchema.FromType<HasRequiredStringObject>();
Assert.NotNull(s.Validator.Validate(c, new HasRequiredStringObject()));
Assert.Null(s.Validator.Validate(c, new HasRequiredStringObject { s = "" }));
Assert.True(c.IsEmpty());
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 16d778a50d1c9374894ef42f892210dd
timeCreated: 1531900562
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,98 +0,0 @@
using NUnit.Framework;
using UniJSON.MsgPack;
namespace UniJSON
{
public class RPCTests
{
[Test]
public void JsonRpcRequestTest()
{
var f = new JsonFormatter();
{
f.Clear();
var l = JsonParser.Parse("{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"num1\",\"params\":[1]}");
f.Request("num1", 1);
var u = new Utf8String(f.GetStoreBytes());
var r = JsonParser.Parse(u);
Assert.AreEqual(
l,
r);
}
{
f.Clear();
f.Request("num2", 2, true);
Assert.AreEqual(
JsonParser.Parse("{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"num2\",\"params\":[2,true]}"),
JsonParser.Parse(new Utf8String(f.GetStoreBytes())));
}
{
f.Clear();
f.Request("num3",
3, true, "abc", false, (string)null, new[] { 1, 2 });
Assert.AreEqual(
JsonParser.Parse("{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"num3\",\"params\":[3,true,\"abc\",false,null,[1,2]]}"),
JsonParser.Parse(new Utf8String(f.GetStoreBytes())));
}
}
[Test]
public void JsonRpcDispatcherTest()
{
var dispatcher = new RpcDispatcher<JsonValue>();
var f = new JsonFormatter();
{
f.Clear();
dispatcher.Register("add", (int a, int b) => a + b);
f.Request("add", 1, 2);
var parsed = JsonParser.Parse(new Utf8String(f.GetStoreBytes()));
f.Clear();
dispatcher.Call(f, parsed["id"].GetInt32(), parsed["method"].GetString(), parsed["params"]);
var response = JsonParser.Parse(new Utf8String(f.GetStoreBytes()));
Assert.AreEqual(3, response["result"].GetInt32());
}
{
string msg = null;
dispatcher.Register("print", (string _msg) => { msg = _msg; });
f.Clear();
f.Request("print", "hoge");
var parsed = JsonParser.Parse(new Utf8String(f.GetStoreBytes()));
f.Clear();
dispatcher.Call(f, parsed["id"].GetInt32(), parsed["method"].GetString(), parsed["params"]);
Assert.AreEqual("hoge", msg);
}
}
[Test]
public void MsgPackRpcDispatcherTest()
{
var dispatcher = new RpcDispatcher<MsgPackValue>();
var f = new MsgPackFormatter();
{
f.GetStore().Clear();
dispatcher.Register("add", (int a, int b) => a + b);
f.Request("add", 1, 2);
var request = MsgPackParser.Parse(f.GetStoreBytes());
Assert.AreEqual(4, request.GetArrayCount());
Assert.AreEqual(MsgPackFormatter.REQUEST_TYPE, request[0].GetInt32());
f.GetStore().Clear();
dispatcher.Call(f, request[1].GetInt32(), request[2].GetString(), request[3]);
var response = MsgPackParser.Parse(f.GetStoreBytes());
Assert.AreEqual(4, response.GetArrayCount());
Assert.AreEqual(MsgPackFormatter.RESPONSE_TYPE, response[0].GetInt32());
Assert.True(response[2].IsNull());
Assert.AreEqual(3, response[3].GetInt32());
}
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 05698e8d4a5f5f64c8482d2d6899301d
timeCreated: 1543250712
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -140,21 +140,7 @@ namespace UniJSON
}
}
{
// reflection
var schema = JsonSchema.FromType<T>();
return (IFormatter f, T value) =>
{
var c = new JsonSchemaValidationContext(value)
{
EnableDiagnosisForNotRequiredFields = true
};
schema.Serialize(f, value, c);
};
}
//throw new NotImplementedException();
throw new NotImplementedException();
}
static Serializer s_serializer;

View File

@@ -1,256 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace UniJSON
{
public static class GenericDeserializer<T, U>
where T : IListTreeItem, IValue<T>
{
public static V[] GenericArrayDeserializer<V>(ListTreeNode<T> s)
{
if (!s.IsArray())
{
throw new ArgumentException("not array: " + s.Value.ValueType);
}
var u = new V[s.GetArrayCount()];
int i = 0;
foreach (var x in s.ArrayItems())
{
x.Deserialize(ref u[i++]);
}
return u;
}
public static List<V> GenericListDeserializer<V>(ListTreeNode<T> s)
{
if (!s.IsArray())
{
throw new ArgumentException("not array: " + s.Value.ValueType);
}
var u = new List<V>(s.GetArrayCount());
foreach (var x in s.ArrayItems())
{
var e = default(V);
x.Deserialize(ref e);
u.Add(e);
}
return u;
}
public static object DefaultDictionaryDeserializer(ListTreeNode<T> s)
{
switch (s.Value.ValueType)
{
case ValueNodeType.Object:
{
var u = new Dictionary<string, object>();
foreach (var kv in s.ObjectItems())
{
//var e = default(object);
//kv.Value.Deserialize(ref e);
u.Add(kv.Key.GetString(), DefaultDictionaryDeserializer(kv.Value));
}
return u;
}
case ValueNodeType.Null:
return null;
case ValueNodeType.Boolean:
return s.GetBoolean();
case ValueNodeType.Integer:
return s.GetInt32();
case ValueNodeType.Number:
return s.GetDouble();
case ValueNodeType.String:
return s.GetString();
default:
throw new NotImplementedException(s.Value.ValueType.ToString());
}
}
/// <summary>
/// Deserialize Dictionary only string key
/// </summary>
/// <typeparam name="V"></typeparam>
/// <param name="s"></param>
/// <returns></returns>
public static Dictionary<string, V> DictionaryDeserializer<V>(ListTreeNode<T> s)
{
var d = new Dictionary<string, V>();
foreach (var kv in s.ObjectItems())
{
var value = default(V);
GenericDeserializer<T, V>.Deserialize(kv.Value, ref value);
d.Add(kv.Key.GetString(), value);
}
return d;
}
delegate void FieldSetter(ListTreeNode<T> s, object o);
static FieldSetter GetFieldDeserializer<V>(FieldInfo fi)
{
return (s, o) =>
{
var u = default(V);
s.Deserialize(ref u);
fi.SetValue(o, u);
};
}
static Func<ListTreeNode<T>, U> GetDeserializer()
{
// primitive
{
var mi = typeof(ListTreeNode<T>).GetMethods().FirstOrDefault(x =>
{
if (!x.Name.StartsWith("Get"))
{
return false;
}
if (!x.Name.EndsWith(typeof(U).Name))
{
return false;
}
var parameters = x.GetParameters();
if (parameters.Length != 0)
{
return false;
}
if (x.ReturnType != typeof(U))
{
return false;
}
return true;
});
if (mi != null)
{
return GenericInvokeCallFactory.StaticFunc<ListTreeNode<T>, U>(mi);
}
}
var target = typeof(U);
if (target.IsArray)
{
var mi = typeof(GenericDeserializer<T, U>).GetMethod("GenericArrayDeserializer",
BindingFlags.Static | BindingFlags.Public);
var g = mi.MakeGenericMethod(target.GetElementType());
return GenericInvokeCallFactory.StaticFunc<ListTreeNode<T>, U>(g);
}
if (target.IsGenericType)
{
if (target.GetGenericTypeDefinition() == typeof(List<>))
{
var mi = typeof(GenericDeserializer<T, U>).GetMethod("GenericListDeserializer",
BindingFlags.Static | BindingFlags.Public);
var g = mi.MakeGenericMethod(target.GetGenericArguments());
return GenericInvokeCallFactory.StaticFunc<ListTreeNode<T>, U>(g);
}
if (target == typeof(Dictionary<string, object>))
{
var mi = typeof(GenericDeserializer<T, U>).GetMethod("DefaultDictionaryDeserializer",
BindingFlags.Static | BindingFlags.Public);
return GenericInvokeCallFactory.StaticFunc<ListTreeNode<T>, U>(mi);
}
else
if (target.GetGenericTypeDefinition() == typeof(Dictionary<,>) &&
target.GetGenericArguments()[0] == typeof(string))
{
var mi = typeof(GenericDeserializer<T, U>).GetMethod("DictionaryDeserializer",
BindingFlags.Static | BindingFlags.Public);
var g = mi.MakeGenericMethod(target.GetGenericArguments()[1]);
return GenericInvokeCallFactory.StaticFunc<ListTreeNode<T>, U>(g);
}
}
{
var schema = JsonSchema.FromType<U>();
return s =>
{
var t = default(U);
schema.Validator.Deserialize(s, ref t);
return t;
};
}
#if false
if (target.IsEnum)
{
var value = Expression.Parameter(typeof(int), "value");
var cast = Expression.Convert(value, target);
var func = Expression.Lambda(cast, value);
var compiled = (Func<int, T>)func.Compile();
return s =>
{
return compiled(s.GetInt32());
};
}
{
var fields = target.GetFields(BindingFlags.Instance | BindingFlags.Public);
var fieldDeserializers = fields.ToDictionary(x => Utf8String.From(x.Name), x =>
{
var mi = typeof(GenericDeserializer<S, T>).GetMethod("GetFieldDeserializer",
BindingFlags.Static|BindingFlags.NonPublic);
var g = mi.MakeGenericMethod(x.FieldType);
return (FieldSetter)g.Invoke(null, new object[] { x });
});
return (S s) =>
{
if (!s.IsMap())
{
throw new ArgumentException(s.ValueType.ToString());
}
var t = (object)default(GenericCreator<S, T>).Create(s);
foreach(var kv in s.ObjectItems())
{
FieldSetter setter;
if (fieldDeserializers.TryGetValue(kv.Key, out setter))
{
setter(kv.Value, t);
}
}
return (T)t;
};
}
#endif
}
public delegate U Deserializer(ListTreeNode<T> node);
public static Deserializer s_deserializer;
public static void Deserialize(ListTreeNode<T> node, ref U value)
{
if (s_deserializer == null)
{
var d = GetDeserializer();
s_deserializer = new Deserializer(d);
}
value = s_deserializer(node);
}
public static void SetCustomDeserializer(Deserializer deserializer)
{
s_deserializer = deserializer;
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 74625bf2a3d6bc64d9d92b08221a8a3d
timeCreated: 1549450914
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -7,7 +7,7 @@ using System.Text;
namespace UniJSON
{
public class JsonFormatter : IFormatter, IRpc
public class JsonFormatter : IFormatter
{
IStore m_w;
protected IStore Store

View File

@@ -1,445 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace UniJSON
{
public class JsonSchema : IEquatable<JsonSchema>
{
public string Schema; // http://json-schema.org/draft-04/schema
#region Annotations
string m_title;
public string Title
{
get { return m_title; }
private set
{
if (value == null)
{
m_title = "";
}
else
{
m_title = value.Trim();
}
}
}
string m_desc;
public string Description
{
get { return m_desc; }
private set
{
if (value == null)
{
m_desc = "";
}
else
{
m_desc = value.Trim();
}
}
}
public object Default
{
get;
private set;
}
#endregion
public IJsonSchemaValidator Validator { get; set; }
/// <summary>
/// Skip validator comparison
/// </summary>
public bool SkipComparison { get; set; }
public object ExplicitIgnorableValue { private get; set; }
public int ExplicitIgnorableItemLength { private get; set; }
public override string ToString()
{
return string.Format("<{0}>", Title);
}
public override int GetHashCode()
{
return 1;
}
public override bool Equals(object obj)
{
var rhs = obj as JsonSchema;
if (rhs == null) return false;
return Equals(rhs);
}
public bool Equals(JsonSchema rhs)
{
// skip comparison
if (SkipComparison) return true;
if (rhs.SkipComparison) return true;
return Validator.Equals(rhs.Validator);
}
public static bool operator ==(JsonSchema obj1, JsonSchema obj2)
{
if (ReferenceEquals(obj1, obj2))
{
return true;
}
if (ReferenceEquals(obj1, null))
{
return false;
}
if (ReferenceEquals(obj2, null))
{
return false;
}
return obj1.Equals(obj2);
}
public static bool operator !=(JsonSchema obj1, JsonSchema obj2)
{
return !(obj1 == obj2);
}
#region FromType
public static JsonSchema FromType<T>()
{
return FromType(typeof(T), null, null);
}
public static JsonSchema FromType(Type t,
BaseJsonSchemaAttribute a = null, // field attribute
ItemJsonSchemaAttribute ia = null
)
{
// class attribute
var aa = t.GetCustomAttributes(typeof(JsonSchemaAttribute), true)
.FirstOrDefault() as JsonSchemaAttribute;
if (a != null)
{
a.Merge(aa);
}
else
{
if (aa == null)
{
a = new JsonSchemaAttribute();
}
else
{
a = aa;
}
}
if (ia == null)
{
ia = t.GetCustomAttributes(typeof(ItemJsonSchemaAttribute), true)
.FirstOrDefault() as ItemJsonSchemaAttribute;
}
IJsonSchemaValidator validator = null;
bool skipComparison = a.SkipSchemaComparison;
if (t == typeof(object))
{
skipComparison = true;
}
if (a.EnumValues != null)
{
try
{
validator = JsonEnumValidator.Create(a.EnumValues, a.EnumSerializationType);
}
catch (Exception)
{
throw new Exception(String.Join(", ", a.EnumValues.Select(x => x.ToString()).ToArray()));
}
}
else if (t.IsEnum)
{
validator = JsonEnumValidator.Create(t, a.EnumSerializationType, a.EnumExcludes);
}
else
{
validator = JsonSchemaValidatorFactory.Create(t, a, ia);
}
var schema = new JsonSchema
{
Title = a.Title,
Description = a.Description,
Validator = validator,
SkipComparison = skipComparison,
ExplicitIgnorableValue = a.ExplicitIgnorableValue,
ExplicitIgnorableItemLength = a.ExplicitIgnorableItemLength,
};
return schema;
}
#endregion
#region FromJson
static ValueNodeType ParseValueType(string type)
{
try
{
return (ValueNodeType)Enum.Parse(typeof(ValueNodeType), type, true);
}
catch (ArgumentException)
{
throw new ArgumentException(string.Format("unknown type: {0}", type));
}
}
Stack<string> m_context = new Stack<string>();
static Utf8String s_ref = Utf8String.From("$ref");
public void Parse(IFileSystemAccessor fs, ListTreeNode<JsonValue> root, string Key)
{
m_context.Push(Key);
var compositionType = default(CompositionType);
var composition = new List<JsonSchema>();
foreach (var kv in root.ObjectItems())
{
switch (kv.Key.GetString())
{
case "$schema":
Schema = kv.Value.GetString();
break;
case "$ref":
{
var refFs = fs.Get(kv.Value.GetString());
// parse JSON
var json = refFs.ReadAllText();
var refRoot = JsonParser.Parse(json);
Parse(refFs, refRoot, "$ref");
}
break;
#region Annotation
case "title":
Title = kv.Value.GetString();
break;
case "description":
Description = kv.Value.GetString();
break;
case "default":
Default = kv.Value;
break;
#endregion
#region Validation
// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.1
case "type":
if (Validator == null)
{
Validator = JsonSchemaValidatorFactory.Create(kv.Value.GetString());
}
break;
case "enum":
Validator = JsonEnumValidator.Create(kv.Value);
break;
case "const":
break;
#endregion
#region Composite
// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.7
case "oneOf":
break;
case "not":
break;
case "anyOf": // composition
case "allOf": // composition
{
compositionType = (CompositionType)Enum.Parse(typeof(CompositionType), kv.Key.GetString(), true);
foreach (var item in kv.Value.ArrayItems())
{
if (item.ContainsKey(s_ref))
{
var sub = JsonSchema.ParseFromPath(fs.Get(item[s_ref].GetString()));
composition.Add(sub);
}
else
{
var sub = new JsonSchema();
sub.Parse(fs, item, compositionType.ToString());
composition.Add(sub);
}
}
Composite(compositionType, composition);
}
break;
#endregion
// http://json-schema.org/latest/json-schema-validation.html#rfc.section.7
case "format":
break;
#region Gltf
case "gltf_detailedDescription":
break;
case "gltf_webgl":
break;
case "gltf_uriType":
break;
#endregion
default:
{
if (Validator != null)
{
if (Validator.FromJsonSchema(fs, kv.Key.GetString(), kv.Value))
{
continue;
}
}
throw new NotImplementedException(string.Format("unknown key: {0}", kv.Key));
}
}
}
m_context.Pop();
if (Validator == null)
{
SkipComparison = true;
}
}
void Composite(CompositionType compositionType, List<JsonSchema> composition)
{
switch (compositionType)
{
case CompositionType.AllOf:
if (composition.Count == 1)
{
// inheritance
if (Validator == null)
{
//Validator = JsonSchemaValidatorFactory.Create(composition[0].Validator.ValueNodeType);
Validator = composition[0].Validator;
}
else
{
Validator.Merge(composition[0].Validator);
}
}
else
{
throw new NotImplementedException();
}
break;
case CompositionType.AnyOf:
if (Validator == null)
{
if (composition.Count == 1)
{
throw new NotImplementedException();
//Validator = composition[0].Validator;
}
else
{
// extend enum
// enum, enum..., type
Validator = JsonEnumValidator.Create(composition, EnumSerializationType.AsString);
}
}
//throw new NotImplementedException();
break;
default:
throw new NotImplementedException();
}
}
public static JsonSchema ParseFromPath(IFileSystemAccessor fs)
{
// parse JSON
var json = fs.ReadAllText();
var root = JsonParser.Parse(json);
// create schema
var schema = new JsonSchema();
schema.Parse(fs, root, "__ParseFromPath__" + fs.ToString());
return schema;
}
#endregion
public void Serialize<T>(IFormatter f, T o, JsonSchemaValidationContext c = null)
{
if (c == null)
{
c = new JsonSchemaValidationContext(o)
{
EnableDiagnosisForNotRequiredFields = true,
};
}
var ex = Validator.Validate(c, o);
if (ex != null)
{
throw ex;
}
Validator.Serialize(f, c, o);
}
public void ToJson(IFormatter f)
{
f.BeginMap(2);
if (!string.IsNullOrEmpty(Title)) { f.Key("title"); f.Value(Title); }
if (!string.IsNullOrEmpty(Description)) { f.Key("description"); f.Value(Description); }
Validator.ToJsonSchema(f);
f.EndMap();
}
public bool IsExplicitlyIgnorableValue<T>(T obj)
{
if (obj == null)
{
return ExplicitIgnorableValue == null;
}
var iter = obj as System.Collections.ICollection;
if (ExplicitIgnorableItemLength != -1 && iter != null)
{
return iter.Count == ExplicitIgnorableItemLength;
}
return obj.Equals(ExplicitIgnorableValue);
}
}
public static class JsonSchemaExtensions
{
public static string Serialize<T>(this JsonSchema s, T o, JsonSchemaValidationContext c = null)
{
var f = new JsonFormatter();
s.Serialize(f, o, c);
return f.ToString();
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 4d98ef4e469916e428284c9155f29059
timeCreated: 1526056149
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -51,7 +51,7 @@ namespace UniJSON
public object[] EnumExcludes;
#endregion
public PropertyExportFlags ExportFlags = PropertyExportFlags.Default;
// public PropertyExportFlags ExportFlags = PropertyExportFlags.Default;
/// <summary>
/// skip validator comparison

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: bebbecaad7b8e70479f6378faadbccbe
folderAsset: yes
timeCreated: 1531812228
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,88 +0,0 @@
using System;
using System.Collections.Generic;
namespace UniJSON
{
public class JsonSchemaValidationContext
{
Stack<string> m_stack = new Stack<string>();
public bool EnableDiagnosisForNotRequiredFields = false;
public JsonSchemaValidationContext(object o)
{
Push(o.GetType().Name);
}
public ActionDisposer Push(object o)
{
m_stack.Push(o.ToString());
return new ActionDisposer(Pop);
}
public void Pop()
{
m_stack.Pop();
}
public bool IsEmpty()
{
return m_stack.Count == 1; // A first element will be remained.
}
public override string ToString()
{
return string.Join(".", m_stack.ToArray(), 0, m_stack.Count);
}
}
public class JsonSchemaValidationException : Exception
{
public Exception Error
{
get; private set;
}
public JsonSchemaValidationException(JsonSchemaValidationContext context, string msg) : base(string.Format("[{0}] {1}", context, msg))
{
}
public JsonSchemaValidationException(JsonSchemaValidationContext context, Exception ex) : base(string.Format("[{0}] {1}", context, ex))
{
Error = ex;
}
}
public interface IJsonSchemaValidator
{
#region JsonSchema
void Merge(IJsonSchemaValidator rhs);
/// <summary>
/// Parse json schema
/// </summary>
/// <param name="fs"></param>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
bool FromJsonSchema(IFileSystemAccessor fs, string key, ListTreeNode<JsonValue> value);
void ToJsonSchema(IFormatter f);
#endregion
#region Serializer
/// <summary>
///
/// </summary>
/// <param name="o"></param>
/// <returns>return null if validate value</returns>
JsonSchemaValidationException Validate<T>(JsonSchemaValidationContext context, T value);
void Serialize<T>(IFormatter f, JsonSchemaValidationContext context, T value);
void Deserialize<T, U>(ListTreeNode<T> src, ref U dst) where T : IListTreeItem, IValue<T>;
#endregion
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: c35476cdb8e1a4541b2f06b9b11141d0
timeCreated: 1531812340
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,300 +0,0 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;
namespace UniJSON
{
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.4
/// </summary>
public class JsonArrayValidator : IJsonSchemaValidator
{
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.4.1
/// </summary>
public JsonSchema Items
{
get; set;
}
// additionalItems
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.4.3
/// </summary>
public int? MaxItems
{
get; set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.4.4
/// </summary>
public int? MinItems
{
get; set;
}
// uniqueItems
// contains
public override int GetHashCode()
{
return 5;
}
public override bool Equals(object obj)
{
var rhs = obj as JsonArrayValidator;
if (rhs == null) return false;
if (Items != rhs.Items) return false;
if (MaxItems != rhs.MaxItems) return false;
if (MinItems != rhs.MinItems) return false;
return true;
}
public void Merge(IJsonSchemaValidator rhs)
{
throw new NotImplementedException();
}
public bool FromJsonSchema(IFileSystemAccessor fs, string key, ListTreeNode<JsonValue> value)
{
switch (key)
{
case "items":
if (value.IsArray())
{
throw new NotImplementedException();
}
else
{
var sub = new JsonSchema();
sub.Parse(fs, value, "items");
Items = sub;
}
return true;
case "additionalItems":
return true;
case "maxItems":
MaxItems = value.GetInt32();
return true;
case "minItems":
MinItems = value.GetInt32();
return true;
case "uniqueItems":
return true;
case "contains":
return true;
}
return false;
}
static class GenericCounter<T>
{
delegate int Counter(T value);
static Counter s_counter;
public static int Count(T value)
{
if (s_counter == null)
{
var t = typeof(T);
if (t.IsArray)
{
var pi = t.GetProperty("Length");
var compiled = (Func<T, int>)((T array) =>
{
return (int)pi.GetValue(array, null);
});
s_counter = new Counter(compiled);
}
else if (t.GetIsGenericList())
{
var pi = t.GetProperty("Count");
var compiled = (Func<T, int>)((T list) =>
{
return (int)pi.GetValue(list, null);
});
s_counter = new Counter(compiled);
}
else
{
throw new NotImplementedException();
}
}
return s_counter(value);
}
}
public JsonSchemaValidationException Validate<T>(JsonSchemaValidationContext context, T o)
{
if (o == null)
{
return new JsonSchemaValidationException(context, "null");
}
var count = GenericCounter<T>.Count(o);
// Empty array is valid
/*if (count == 0)
{
return new JsonSchemaValidationException(context, "empty");
}*/
if (MaxItems.HasValue && count > MaxItems.Value)
{
return new JsonSchemaValidationException(context, "maxItems");
}
if (MinItems.HasValue && count < MinItems.Value)
{
return new JsonSchemaValidationException(context, "minItems");
}
if (Items == null)
{
return null; // There are no json schema for items, success
}
var v = Items.Validator;
var t = o.GetType();
IEnumerable iter = null;
if (t.IsArray)
{
iter = o as Array;
}
else if (t.GetIsGenericList())
{
iter = o as IList;
}
else
{
return new JsonSchemaValidationException(context, "non iterable object");
}
foreach(var e in iter)
{
var ex = v.Validate(context, e);
if (ex != null)
{
return ex;
}
};
return null;
}
static void ArraySerializer<U>(IJsonSchemaValidator v, IFormatter f, JsonSchemaValidationContext c, U[] array)
{
f.BeginList(array.Length);
{
//int i = 0;
foreach (var x in array)
{
//using (c.Push(i++))
{
v.Serialize(f, c, x);
}
}
}
f.EndList();
}
static void ListSerializer<U>(IJsonSchemaValidator v, IFormatter f, JsonSchemaValidationContext c, List<U> list)
{
f.BeginList(list.Count);
{
//int i = 0;
foreach (var x in list)
{
//using (c.Push(i++))
{
v.Serialize(f, c, x);
}
}
}
f.EndList();
}
static class GenericSerializer<T>
{
delegate void Serializer(IJsonSchemaValidator v, IFormatter f, JsonSchemaValidationContext c, T o);
static Serializer s_serializer;
public static void Serialize(IJsonSchemaValidator v, IFormatter f, JsonSchemaValidationContext c, T o)
{
if (s_serializer == null)
{
var t = typeof(T);
MethodInfo g = null;
if (t.IsArray)
{
var mi = typeof(JsonArrayValidator).GetMethod("ArraySerializer",
BindingFlags.Static | BindingFlags.NonPublic);
g = mi.MakeGenericMethod(t.GetElementType());
}
else if (t.GetIsGenericList())
{
// ToDo: IList
var mi = typeof(JsonArrayValidator).GetMethod("ListSerializer",
BindingFlags.Static | BindingFlags.NonPublic);
g = mi.MakeGenericMethod(t.GetGenericArguments());
}
else
{
throw new NotImplementedException();
}
var compiled = (Action<
IJsonSchemaValidator,
IFormatter,
JsonSchemaValidationContext,
T>)
GenericInvokeCallFactory.StaticAction<
IJsonSchemaValidator,
IFormatter,
JsonSchemaValidationContext,
T>(g);
s_serializer = new Serializer(compiled);
}
s_serializer(v, f, c, o);
}
}
public void Serialize<T>(IFormatter f, JsonSchemaValidationContext c, T o)
{
GenericSerializer<T>.Serialize(Items.Validator, f, c, o);
}
public void ToJsonSchema(IFormatter f)
{
f.Key("type"); f.Value("array");
if (Items != null)
{
f.Key("items");
Items.ToJson(f);
}
}
public void Deserialize<T, U>(ListTreeNode<T> src, ref U dst)
where T : IListTreeItem, IValue<T>
{
src.Deserialize(ref dst);
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 6144a646f2f535641885a006024771a4
timeCreated: 1531812663
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,51 +0,0 @@
using System;
namespace UniJSON
{
public class JsonBoolValidator : IJsonSchemaValidator
{
public override int GetHashCode()
{
return 1;
}
public override bool Equals(object obj)
{
var rhs = obj as JsonBoolValidator;
if (rhs == null) return false;
return true;
}
public void Merge(IJsonSchemaValidator obj)
{
throw new NotImplementedException();
}
public bool FromJsonSchema(IFileSystemAccessor fs, string key, ListTreeNode<JsonValue> value)
{
return false;
}
public void ToJsonSchema(IFormatter f)
{
f.Key("type"); f.Value("boolean");
}
public JsonSchemaValidationException Validate<T>(JsonSchemaValidationContext c, T value)
{
return null;
}
public void Serialize<T>(IFormatter f, JsonSchemaValidationContext c, T value)
{
f.Serialize(value);
}
public void Deserialize<T, U>(ListTreeNode<T> src, ref U dst)
where T : IListTreeItem, IValue<T>
{
dst = GenericCast<bool, U>.Cast(src.GetBoolean());
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 2a6454bbd9b910d499702d2ba8270ea0
timeCreated: 1531812394
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,307 +0,0 @@
using System;
using System.Linq;
using System.Collections.Generic;
namespace UniJSON
{
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5
/// </summary>
public class JsonDictionaryValidator<T> : IJsonSchemaValidator
{
public JsonDictionaryValidator()
{
AdditionalProperties = JsonSchema.FromType<T>();
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.1
/// </summary>
public int MaxProperties
{
get; set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.2
/// </summary>
public int MinProperties
{
get; set;
}
List<string> m_required = new List<string>();
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.3
/// </summary>
public List<string> Required
{
get { return m_required; }
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.5
/// </summary>
public string PatternProperties
{
get; private set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.6
/// </summary>
public JsonSchema AdditionalProperties
{
get; set;
}
Dictionary<string, string[]> m_dependencies;
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.7
/// </summary>
public Dictionary<string, string[]> Dependencies
{
get
{
if (m_dependencies == null)
{
m_dependencies = new Dictionary<string, string[]>();
}
return m_dependencies;
}
}
public override int GetHashCode()
{
return 6;
}
public override bool Equals(object obj)
{
var rhs = obj as JsonObjectValidator;
if (rhs == null)
{
return false;
}
if (Required.Count != rhs.Required.Count)
{
return false;
}
if (!Required.OrderBy(x => x).SequenceEqual(rhs.Required.OrderBy(x => x)))
{
return false;
}
if (Dependencies.Count != rhs.Dependencies.Count)
{
return false;
}
foreach (var kv in Dependencies)
{
if (!kv.Value.OrderBy(x => x).SequenceEqual(rhs.Dependencies[kv.Key].OrderBy(x => x)))
{
return false;
}
}
if (AdditionalProperties == null
&& rhs.AdditionalProperties == null)
{
// ok
}
else if (AdditionalProperties == null)
{
return false;
}
else if (rhs.AdditionalProperties == null)
{
return false;
}
else
{
if (!AdditionalProperties.Equals(rhs.AdditionalProperties))
{
return false;
}
}
return true;
}
public void Merge(IJsonSchemaValidator obj)
{
var rhs = obj as JsonObjectValidator;
if (rhs == null)
{
throw new ArgumentException();
}
foreach (var x in rhs.Required)
{
this.Required.Add(x);
}
if (rhs.AdditionalProperties != null)
{
if (AdditionalProperties != null)
{
throw new NotImplementedException();
}
AdditionalProperties = rhs.AdditionalProperties;
}
}
public bool FromJsonSchema(IFileSystemAccessor fs, string key, ListTreeNode<JsonValue> value)
{
switch (key)
{
case "maxProperties":
MaxProperties = value.GetInt32();
return true;
case "minProperties":
MinProperties = value.GetInt32();
return true;
case "required":
{
foreach (var req in value.ArrayItems())
{
m_required.Add(req.GetString());
}
}
return true;
case "patternProperties":
PatternProperties = value.GetString();
return true;
case "additionalProperties":
{
var sub = new JsonSchema();
sub.Parse(fs, value, "additionalProperties");
AdditionalProperties = sub;
}
return true;
case "dependencies":
{
foreach (var kv in value.ObjectItems())
{
Dependencies.Add(kv.Key.GetString(), kv.Value.ArrayItems().Select(x => x.GetString()).ToArray());
}
}
return true;
case "propertyNames":
return true;
}
return false;
}
public void ToJsonSchema(IFormatter f)
{
f.Key("type"); f.Value("object");
}
public JsonSchemaValidationException Validate<S>(JsonSchemaValidationContext c, S o)
{
if (o == null)
{
return new JsonSchemaValidationException(c, "null");
}
var d = o as IDictionary<string, T>;
if (d == null)
{
return new JsonSchemaValidationException(c, "not dictionary");
}
if (Required != null)
{
foreach (var x in Required)
{
using (c.Push(x))
{
// ToDo
}
}
}
if (AdditionalProperties != null)
{
foreach (var kv in d)
{
using (c.Push(kv.Key))
{
var result = AdditionalProperties.Validator.Validate(c, kv.Value);
if (result != null)
{
return result;
}
}
}
}
return null;
}
Dictionary<string, object> m_validValueMap = new Dictionary<string, object>();
public void Serialize<S>(IFormatter f, JsonSchemaValidationContext c, S o)
{
// validate properties
m_validValueMap.Clear();
var dict = o as Dictionary<string, T>;
f.BeginMap(dict.Count);
{
foreach (var kv in dict)
{
// key
f.Key(kv.Key);
// value
//using (c.Push(kv.Key))
{
AdditionalProperties.Validator.Serialize(f, c, kv.Value);
}
}
}
f.EndMap();
}
public void Deserialize<U, V>(ListTreeNode<U> src, ref V dst)
where U : IListTreeItem, IValue<U>
{
src.Deserialize(ref dst);
}
}
public static class JsonDictionaryValidator
{
public static JsonDictionaryValidator<T> Create<T>()
{
return new JsonDictionaryValidator<T>();
}
#region AOT
public static JsonDictionaryValidator<Single> CreateSingle()
{
return Create<Single>();
}
public static JsonDictionaryValidator<Int32> CreateInt32()
{
return Create<Int32>();
}
public static JsonDictionaryValidator<Boolean> CreateBoolean()
{
return Create<Boolean>();
}
#endregion
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: ccee0323c35d40d498d45b207124fe7e
timeCreated: 1531812708
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,441 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace UniJSON
{
public static class JsonEnumValidator
{
public static IJsonSchemaValidator Create(ListTreeNode<JsonValue> value)
{
foreach (var x in value.ArrayItems())
{
if (x.IsInteger() || x.IsFloat())
{
return JsonIntEnumValidator.Create(value.ArrayItems()
.Where(y => y.IsInteger() || y.IsFloat())
.Select(y => y.GetInt32())
);
}
else if (x.IsString())
{
return JsonStringEnumValidator.Create(value.ArrayItems()
.Where(y => y.IsString())
.Select(y => y.GetString())
, EnumSerializationType.AsString
);
}
else
{
}
}
throw new NotImplementedException();
}
public static IJsonSchemaValidator Create(IEnumerable<JsonSchema> composition, EnumSerializationType type)
{
foreach (var x in composition)
{
if (x.Validator is JsonStringEnumValidator)
{
return JsonStringEnumValidator.Create(composition
.Select(y => y.Validator as JsonStringEnumValidator)
.Where(y => y != null)
.SelectMany(y => y.Values),
type
);
}
if (x.Validator is JsonIntEnumValidator)
{
return JsonIntEnumValidator.Create(composition
.Select(y => y.Validator as JsonIntEnumValidator)
.Where(y => y != null)
.SelectMany(y => y.Values)
);
}
}
throw new NotImplementedException();
}
static IEnumerable<string> GetStringValues(Type t, object[] excludes, Func<String, String> filter)
{
foreach (var x in Enum.GetValues(t))
{
if (excludes == null || !excludes.Contains(x))
{
yield return filter(x.ToString());
}
}
}
static IEnumerable<int> GetIntValues(Type t, object[] excludes)
{
foreach (var x in Enum.GetValues(t))
{
if (excludes == null || !excludes.Contains(x))
{
yield return (int)x;
}
}
}
public static IJsonSchemaValidator Create(Type t, EnumSerializationType serializationType, object[] excludes)
{
switch (serializationType)
{
case EnumSerializationType.AsInt:
return JsonIntEnumValidator.Create(GetIntValues(t, excludes));
case EnumSerializationType.AsString:
return JsonStringEnumValidator.Create(GetStringValues(t, excludes, x => x), serializationType);
case EnumSerializationType.AsLowerString:
return JsonStringEnumValidator.Create(GetStringValues(t, excludes, x => x.ToLower()), serializationType);
case EnumSerializationType.AsUpperString:
return JsonStringEnumValidator.Create(GetStringValues(t, excludes, x => x.ToUpper()), serializationType);
default:
throw new NotImplementedException();
}
}
public static IJsonSchemaValidator Create(object[] values, EnumSerializationType type)
{
foreach (var x in values)
{
if (x is string)
{
return JsonStringEnumValidator.Create(values.Select(y => (string)y), type);
}
if (x is int)
{
return JsonIntEnumValidator.Create(values.Select(y => (int)y));
}
}
throw new NotImplementedException();
}
}
public class JsonStringEnumValidator : IJsonSchemaValidator
{
EnumSerializationType SerializationType;
public String[] Values
{
get; set;
}
JsonStringEnumValidator(IEnumerable<string> values, EnumSerializationType type)
{
SerializationType = type;
switch (SerializationType)
{
case EnumSerializationType.AsString:
Values = values.ToArray();
break;
case EnumSerializationType.AsLowerString:
Values = values.Select(x => x.ToLower()).ToArray();
break;
case EnumSerializationType.AsUpperString:
Values = values.Select(x => x.ToUpper()).ToArray();
break;
case EnumSerializationType.AsInt:
throw new ArgumentException("JsonStringEnumValidator not allow AsInt");
default:
throw new NotImplementedException("");
}
}
public static JsonStringEnumValidator Create(IEnumerable<string> values, EnumSerializationType type)
{
return new JsonStringEnumValidator(values, type);
}
public override int GetHashCode()
{
return 7;
}
public override bool Equals(object obj)
{
var rhs = obj as JsonStringEnumValidator;
if (rhs == null) return false;
if (Values.Length != rhs.Values.Length) return false;
var l = Values.OrderBy(x => x).GetEnumerator();
var r = rhs.Values.OrderBy(x => x).GetEnumerator();
while (l.MoveNext() && r.MoveNext())
{
if (l.Current != r.Current)
{
return false;
}
}
return true;
}
public void Merge(IJsonSchemaValidator obj)
{
throw new NotImplementedException();
}
public bool FromJsonSchema(IFileSystemAccessor fs, string key, ListTreeNode<JsonValue> value)
{
throw new NotImplementedException();
}
public void ToJsonSchema(IFormatter f)
{
f.Key("type"); f.Value("string");
f.Key("enum");
f.BeginList(Values.Length);
foreach (var x in Values)
{
f.Value(x);
}
f.EndList();
}
public JsonSchemaValidationException Validate<T>(JsonSchemaValidationContext c, T o)
{
if (o == null)
{
return new JsonSchemaValidationException(c, "null");
}
var t = o.GetType();
string value = null;
if (t.IsEnum)
{
value = Enum.GetName(t, o);
}
else
{
value = GenericCast<T, string>.Cast(o);
}
if (SerializationType == EnumSerializationType.AsLowerString)
{
value = value.ToLower();
}
else if (SerializationType == EnumSerializationType.AsUpperString)
{
value = value.ToUpper();
}
if (Values.Contains(value))
{
return null;
}
else
{
return new JsonSchemaValidationException(c, string.Format("{0} is not valid enum", o));
}
}
public static class GenericSerializer<T>
{
delegate void Serializer(JsonStringEnumValidator v,
IFormatter f, JsonSchemaValidationContext c, T o);
static Serializer s_serializer;
public static void Serialize(JsonStringEnumValidator validator,
IFormatter f, JsonSchemaValidationContext c, T o)
{
if (s_serializer == null)
{
var t = typeof(T);
if (t.IsEnum)
{
s_serializer = (vv, ff, cc, oo) =>
{
var value = Enum.GetName(t, oo);
if (vv.SerializationType == EnumSerializationType.AsLowerString)
{
value = value.ToLower();
}
else if (vv.SerializationType == EnumSerializationType.AsUpperString)
{
value = value.ToUpper();
}
ff.Value(value);
};
}
else if (t == typeof(string))
{
s_serializer = (vv, ff, cc, oo) =>
{
var value = GenericCast<T, string>.Cast(oo);
if (vv.SerializationType == EnumSerializationType.AsLowerString)
{
value = value.ToLower();
}
else if (vv.SerializationType == EnumSerializationType.AsUpperString)
{
value = value.ToUpper();
}
ff.Value(value);
};
}
else
{
throw new NotImplementedException();
}
}
s_serializer(validator, f, c, o);
}
}
public void Serialize<T>(IFormatter f, JsonSchemaValidationContext c, T o)
{
GenericSerializer<T>.Serialize(this, f, c, o);
}
static class GenericDeserializer<T, U>
where T : IListTreeItem, IValue<T>
{
delegate U Deserializer(ListTreeNode<T> src);
static Deserializer s_d;
public static void Deserialize(ListTreeNode<T> src, ref U t)
{
if (s_d == null)
{
if (typeof(U).IsEnum)
{
// enum from string
var mi = typeof(Enum).GetMethods(BindingFlags.Static | BindingFlags.Public).First(
x => x.Name == "Parse" && x.GetParameters().Length == 3
);
var enumParse = GenericInvokeCallFactory.StaticFunc<Type, string, bool, object>(mi);
s_d = x =>
{
var enumValue = enumParse(typeof(U), x.GetString(), true);
return GenericCast<object, U>.Cast(enumValue);
};
}
else
{
s_d = x => GenericCast<string, U>.Cast(x.GetString());
}
}
t = s_d(src);
}
}
public void Deserialize<T, U>(ListTreeNode<T> src, ref U dst)
where T : IListTreeItem, IValue<T>
{
GenericDeserializer<T, U>.Deserialize(src, ref dst);
}
}
public class JsonIntEnumValidator : IJsonSchemaValidator
{
public int[] Values
{
get; set;
}
public static JsonIntEnumValidator Create(IEnumerable<int> values)
{
return new JsonIntEnumValidator
{
Values = values.ToArray()
};
}
public override int GetHashCode()
{
return 7;
}
public override bool Equals(object obj)
{
var rhs = obj as JsonIntEnumValidator;
if (rhs == null) return false;
if (Values.Length != rhs.Values.Length) return false;
var l = Values.OrderBy(x => x).GetEnumerator();
var r = rhs.Values.OrderBy(x => x).GetEnumerator();
while (l.MoveNext() && r.MoveNext())
{
if (l.Current != r.Current)
{
return false;
}
}
return true;
}
public void Merge(IJsonSchemaValidator obj)
{
throw new NotImplementedException();
}
public bool FromJsonSchema(IFileSystemAccessor fs, string key, ListTreeNode<JsonValue> value)
{
throw new NotImplementedException();
}
public void ToJsonSchema(IFormatter f)
{
f.Key("type"); f.Value("integer");
}
public JsonSchemaValidationException Validate<T>(JsonSchemaValidationContext c, T o)
{
if (Values.Contains(GenericCast<T, int>.Cast(o)))
{
return null;
}
else
{
return new JsonSchemaValidationException(c, string.Format("{0} is not valid enum", o));
}
}
public void Serialize<T>(IFormatter f, JsonSchemaValidationContext c, T o)
{
f.Serialize(GenericCast<T, int>.Cast(o));
}
static class GenericDeserializer<T, U>
where T : IListTreeItem, IValue<T>
{
delegate U Deserializer(ListTreeNode<T> src);
static Deserializer s_d;
public static void Deserialize(ListTreeNode<T> src, ref U dst)
{
if (s_d == null)
{
// enum from int
s_d = s => GenericCast<int, U>.Cast(s.GetInt32());
}
dst = s_d(src);
}
}
public void Deserialize<T, U>(ListTreeNode<T> src, ref U dst)
where T : IListTreeItem, IValue<T>
{
GenericDeserializer<T, U>.Deserialize(src, ref dst);
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: f503fff7ab8dcf74abc9dd8073aa9062
timeCreated: 1531812758
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,430 +0,0 @@
using System;
namespace UniJSON
{
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#numeric
/// </summary>
public class JsonIntValidator : IJsonSchemaValidator
{
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.2.1
/// </summary>
public int? MultipleOf
{
get; set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.2.2
/// </summary>
public int? Maximum
{
get; set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.2.3
/// </summary>
public bool ExclusiveMaximum
{
get; set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.2.4
/// </summary>
public int? Minimum
{
get; set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.2.5
/// </summary>
public bool ExclusiveMinimum
{
get; set;
}
public override int GetHashCode()
{
return 2;
}
public override bool Equals(object obj)
{
var rhs = obj as JsonIntValidator;
if (rhs == null) return false;
if (MultipleOf != rhs.MultipleOf)
{
Console.WriteLine("MultipleOf");
return false;
}
if (Maximum != rhs.Maximum)
{
Console.WriteLine("Maximum");
return false;
}
if (ExclusiveMaximum != rhs.ExclusiveMaximum)
{
Console.WriteLine("ExclusiveMaximum");
return false;
}
if (Minimum != rhs.Minimum)
{
Console.WriteLine("Minimum");
return false;
}
if (ExclusiveMinimum != rhs.ExclusiveMinimum)
{
Console.WriteLine("ExclusiveMinimum");
return false;
}
return true;
}
public bool FromJsonSchema(IFileSystemAccessor fs, string key, ListTreeNode<JsonValue> value)
{
switch (key)
{
case "multipleOf":
MultipleOf = value.GetInt32();
return true;
case "maximum":
Maximum = value.GetInt32();
return true;
case "exclusiveMaximum":
ExclusiveMaximum = value.GetBoolean();
return true;
case "minimum":
Minimum = value.GetInt32();
return true;
case "exclusiveMinimum":
ExclusiveMinimum = value.GetBoolean();
return true;
}
return false;
}
public void ToJsonSchema(IFormatter f)
{
f.Key("type"); f.Value("integer");
if (Minimum.HasValue)
{
f.Key("minimum"); f.Value(Minimum.Value);
}
if (Maximum.HasValue)
{
f.Key("maximum"); f.Value(Maximum.Value);
}
}
public void Merge(IJsonSchemaValidator obj)
{
var rhs = obj as JsonIntValidator;
if (rhs == null)
{
throw new ArgumentException();
}
MultipleOf = rhs.MultipleOf;
Maximum = rhs.Maximum;
ExclusiveMaximum = rhs.ExclusiveMaximum;
Minimum = rhs.Minimum;
ExclusiveMinimum = rhs.ExclusiveMinimum;
}
public JsonSchemaValidationException Validate<T>(JsonSchemaValidationContext c, T o)
{
try
{
var value = GenericCast<T, int>.Cast(o);
if (Minimum.HasValue)
{
if (ExclusiveMinimum)
{
if (value > Minimum.Value)
{
// ok
}
else
{
return new JsonSchemaValidationException(c, string.Format("minimum: ! {0}>{1}", value, Minimum.Value));
}
}
else
{
if (value >= Minimum.Value)
{
// ok
}
else
{
return new JsonSchemaValidationException(c, string.Format("minimum: ! {0}>={1}", value, Minimum.Value));
}
}
}
if (Maximum.HasValue)
{
if (ExclusiveMaximum)
{
if (value < Maximum.Value)
{
// ok
}
else
{
return new JsonSchemaValidationException(c, string.Format("maximum: ! {0}<{1}", value, Maximum.Value));
}
}
else
{
if (value <= Maximum.Value)
{
// ok
}
else
{
return new JsonSchemaValidationException(c, string.Format("maximum: ! {0}<={1}", value, Maximum.Value));
}
}
}
if (MultipleOf.HasValue && value % MultipleOf.Value != 0)
{
return new JsonSchemaValidationException(c, string.Format("multipleOf: {0}%{1}", value, MultipleOf.Value));
}
return null;
}
catch (Exception ex)
{
return new JsonSchemaValidationException(c, ex);
}
}
public void Serialize<T>(IFormatter f, JsonSchemaValidationContext c, T o)
{
f.Serialize(GenericCast<T, int>.Cast(o));
}
public void Deserialize<T, U>(ListTreeNode<T> src, ref U dst)
where T : IListTreeItem, IValue<T>
{
dst = GenericCast<int, U>.Cast(src.GetInt32());
}
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#numeric
/// </summary>
public class JsonNumberValidator : IJsonSchemaValidator
{
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.2.1
/// </summary>
public double? MultipleOf
{
get; set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.2.2
/// </summary>
public double? Maximum
{
get; set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.2.3
/// </summary>
public bool ExclusiveMaximum
{
get; set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.2.4
/// </summary>
public double? Minimum
{
get; set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.2.5
/// </summary>
public bool ExclusiveMinimum
{
get; set;
}
public override int GetHashCode()
{
return 3;
}
public override bool Equals(object obj)
{
var rhs = obj as JsonNumberValidator;
if (rhs == null) return false;
if (MultipleOf != rhs.MultipleOf) return false;
if (Maximum != rhs.Maximum) return false;
if (ExclusiveMaximum != rhs.ExclusiveMaximum) return false;
if (Minimum != rhs.Minimum) return false;
if (ExclusiveMinimum != rhs.ExclusiveMinimum) return false;
return true;
}
public void Merge(IJsonSchemaValidator rhs)
{
throw new NotImplementedException();
}
public bool FromJsonSchema(IFileSystemAccessor fs, string key, ListTreeNode<JsonValue> value)
{
switch (key)
{
case "multipleOf":
MultipleOf = value.GetDouble();
return true;
case "maximum":
Maximum = value.GetDouble();
return true;
case "exclusiveMaximum":
ExclusiveMaximum = value.GetBoolean();
return true;
case "minimum":
Minimum = value.GetDouble();
return true;
case "exclusiveMinimum":
ExclusiveMinimum = value.GetBoolean();
return true;
}
return false;
}
public void ToJsonSchema(IFormatter f)
{
f.Key("type"); f.Value("number");
if (Minimum.HasValue)
{
f.Key("minimum"); f.Value(Minimum.Value);
}
if (Maximum.HasValue)
{
f.Key("maximum"); f.Value(Maximum.Value);
}
}
public JsonSchemaValidationException Validate<T>(JsonSchemaValidationContext c, T o)
{
try
{
var value = Convert.ToDouble(o);
if (Minimum.HasValue)
{
if (ExclusiveMinimum)
{
if (value > Minimum.Value)
{
// ok
}
else
{
return new JsonSchemaValidationException(c, string.Format("minimum: ! {0}>{1}", value, Minimum.Value));
}
}
else
{
if (value >= Minimum.Value)
{
// ok
}
else
{
return new JsonSchemaValidationException(c, string.Format("minimum: ! {0}>={1}", value, Minimum.Value));
}
}
}
if (Maximum.HasValue)
{
if (ExclusiveMaximum)
{
if (value < Maximum.Value)
{
// ok
}
else
{
return new JsonSchemaValidationException(c, string.Format("maximum: ! {0}<{1}", value, Maximum.Value));
}
}
else
{
if (value <= Maximum.Value)
{
// ok
}
else
{
return new JsonSchemaValidationException(c, string.Format("maximum: ! {0}<={1}", value, Maximum.Value));
}
}
}
/*
if (MultipleOf.HasValue && value % MultipleOf.Value != 0)
{
return new JsonSchemaValidationException(c, string.Format("multipleOf: {0}%{1}", value, MultipleOf.Value));
}
*/
if (MultipleOf.HasValue)
{
throw new NotImplementedException();
}
return null;
}
catch (Exception ex)
{
return new JsonSchemaValidationException(c, ex);
}
}
public void Serialize<T>(IFormatter f, JsonSchemaValidationContext c, T o)
{
f.Serialize(o);
}
public void Deserialize<T, U>(ListTreeNode<T> src, ref U dst)
where T : IListTreeItem, IValue<T>
{
dst = GenericCast<double, U>.Cast(src.GetDouble());
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: fb1d83ccd68b93c47821000b53471eae
timeCreated: 1531812526
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,686 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace UniJSON
{
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5
/// </summary>
public class JsonObjectValidator : IJsonSchemaValidator
{
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.1
/// </summary>
public int MaxProperties
{
get; set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.2
/// </summary>
public int MinProperties
{
get; set;
}
HashSet<string> m_required = new HashSet<string>();
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.3
/// </summary>
public HashSet<string> Required
{
get { return m_required; }
}
Dictionary<string, JsonSchema> m_props;
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.4
/// </summary>
public Dictionary<string, JsonSchema> Properties
{
get
{
if (m_props == null)
{
m_props = new Dictionary<string, JsonSchema>();
}
return m_props;
}
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.5
/// </summary>
public string PatternProperties
{
get; private set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.6
/// </summary>
public JsonSchema AdditionalProperties
{
get; set;
}
Dictionary<string, string[]> m_dependencies;
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.5.7
/// </summary>
public Dictionary<string, string[]> Dependencies
{
get
{
if (m_dependencies == null)
{
m_dependencies = new Dictionary<string, string[]>();
}
return m_dependencies;
}
}
public void AddProperty(IFileSystemAccessor fs, string key, ListTreeNode<JsonValue> value)
{
var sub = new JsonSchema();
sub.Parse(fs, value, key);
if (Properties.ContainsKey(key))
{
if (sub.Validator != null)
{
Properties[key].Validator.Merge(sub.Validator);
}
}
else
{
Properties.Add(key, sub);
}
}
public override int GetHashCode()
{
return 6;
}
public override bool Equals(object obj)
{
var rhs = obj as JsonObjectValidator;
if (rhs == null)
{
return false;
}
if (Properties.Count != rhs.Properties.Count)
{
return false;
}
foreach (var pair in Properties)
{
JsonSchema value;
if (rhs.Properties.TryGetValue(pair.Key, out value))
{
#if true
if (!value.Equals(pair.Value))
{
Console.WriteLine(string.Format("{0} is not equals", pair.Key));
var l = pair.Value.Validator;
var r = value.Validator;
return false;
}
#else
// key name match
return true;
#endif
}
else
{
return false;
}
}
if (Required.Count != rhs.Required.Count)
{
return false;
}
if (!Required.OrderBy(x => x).SequenceEqual(rhs.Required.OrderBy(x => x)))
{
return false;
}
if (Dependencies.Count != rhs.Dependencies.Count)
{
return false;
}
foreach (var kv in Dependencies)
{
if (!kv.Value.OrderBy(x => x).SequenceEqual(rhs.Dependencies[kv.Key].OrderBy(x => x)))
{
return false;
}
}
if (AdditionalProperties == null
&& rhs.AdditionalProperties == null)
{
// ok
}
else if (AdditionalProperties == null)
{
return false;
}
else if (rhs.AdditionalProperties == null)
{
return false;
}
else
{
if (!AdditionalProperties.Equals(rhs.AdditionalProperties))
{
return false;
}
}
return true;
}
public void Merge(IJsonSchemaValidator obj)
{
var rhs = obj as JsonObjectValidator;
if (rhs == null)
{
throw new ArgumentException();
}
foreach (var x in rhs.Properties)
{
if (this.Properties.ContainsKey(x.Key))
{
this.Properties[x.Key] = x.Value;
}
else
{
this.Properties.Add(x.Key, x.Value);
}
}
foreach (var x in rhs.Required)
{
this.Required.Add(x);
}
if (rhs.AdditionalProperties != null)
{
if (AdditionalProperties != null)
{
throw new NotImplementedException();
}
AdditionalProperties = rhs.AdditionalProperties;
}
}
public bool FromJsonSchema(IFileSystemAccessor fs, string key, ListTreeNode<JsonValue> value)
{
switch (key)
{
case "maxProperties":
MaxProperties = value.GetInt32();
return true;
case "minProperties":
MinProperties = value.GetInt32();
return true;
case "required":
{
foreach (var req in value.ArrayItems())
{
m_required.Add(req.GetString());
}
}
return true;
case "properties":
{
foreach (var prop in value.ObjectItems())
{
AddProperty(fs, prop.Key.GetString(), prop.Value);
}
}
return true;
case "patternProperties":
PatternProperties = value.GetString();
return true;
case "additionalProperties":
{
var sub = new JsonSchema();
sub.Parse(fs, value, "additionalProperties");
AdditionalProperties = sub;
}
return true;
case "dependencies":
{
foreach (var kv in value.ObjectItems())
{
Dependencies.Add(kv.Key.GetString(), kv.Value.ArrayItems().Select(x => x.GetString()).ToArray());
}
}
return true;
case "propertyNames":
return true;
}
return false;
}
public void ToJsonSchema(IFormatter f)
{
f.Key("type"); f.Value("object");
if (Properties.Count > 0)
{
f.Key("properties");
f.BeginMap(Properties.Count);
foreach (var kv in Properties)
{
f.Key(kv.Key);
kv.Value.ToJson(f);
}
f.EndMap();
}
}
static class GenericFieldView<T>
{
public static FieldInfo[] GetFields()
{
var t = typeof(T);
return t.GetFields(BindingFlags.Instance | BindingFlags.Public);
}
public static void CreateFieldProcessors<G, D>(
Func<FieldInfo, D> creator,
Dictionary<string, D> processors
)
{
foreach (var fi in GetFields())
{
processors.Add(fi.Name, creator(fi));
}
}
}
internal class ValidationResult
{
public bool IsIgnorable;
public JsonSchemaValidationException Ex;
}
public static class GenericValidator<T>
{
class ObjectValidator
{
delegate JsonSchemaValidationException FieldValidator(
JsonSchema s, JsonSchemaValidationContext c, T o, out bool isIgnorable);
Dictionary<string, FieldValidator> m_validators;
static FieldValidator CreateFieldValidator(FieldInfo fi)
{
var mi = typeof(ObjectValidator).GetMethod("_CreateFieldValidator",
BindingFlags.Static | BindingFlags.NonPublic)
;
var g = mi.MakeGenericMethod(fi.FieldType);
return GenericInvokeCallFactory.StaticFunc<FieldInfo, FieldValidator>(g)(fi);
}
static FieldValidator _CreateFieldValidator<U>(FieldInfo fi)
{
var getter = (Func<T, U>)((t) => (U)fi.GetValue(t));
return (JsonSchema s, JsonSchemaValidationContext c, T o, out bool isIgnorable) =>
{
var v = s.Validator;
using (c.Push(fi.Name))
{
var field = getter(o);
var ex = v.Validate(c, field);
isIgnorable = ex != null && s.IsExplicitlyIgnorableValue(field);
return ex;
}
};
}
public ObjectValidator()
{
var validators = new Dictionary<string, FieldValidator>();
GenericFieldView<T>.CreateFieldProcessors<ObjectValidator, FieldValidator>(
CreateFieldValidator, validators);
m_validators = validators;
}
public JsonSchemaValidationException ValidateProperty(
HashSet<string> required,
KeyValuePair<string, JsonSchema> property,
JsonSchemaValidationContext c,
T o,
out bool isIgnorable
)
{
var fieldName = property.Key;
var schema = property.Value;
isIgnorable = false;
FieldValidator fv;
if (m_validators.TryGetValue(fieldName, out fv))
{
var isRequired = required != null && required.Contains(fieldName);
bool isMemberIgnorable;
var ex = fv(schema, c, o, out isMemberIgnorable);
if (ex != null)
{
isIgnorable = !isRequired && isMemberIgnorable;
if (isRequired // required fields must be checked
|| c.EnableDiagnosisForNotRequiredFields)
{
return ex;
}
}
}
return null;
}
public JsonSchemaValidationException Validate(
HashSet<string> required,
Dictionary<string, JsonSchema> properties,
JsonSchemaValidationContext c, T o)
{
foreach (var kv in properties)
{
bool isIgnorable;
var ex = ValidateProperty(required, kv, c, o, out isIgnorable);
if (ex != null && !isIgnorable)
{
return ex;
}
}
return null;
}
public void ValidationResults
(HashSet<string> required,
Dictionary<string, JsonSchema> properties,
JsonSchemaValidationContext c, T o,
Dictionary<string, ValidationResult> results)
{
foreach (var kv in properties)
{
bool isIgnorable;
var ex = ValidateProperty(required, kv, c, o, out isIgnorable);
results.Add(kv.Key, new ValidationResult {
IsIgnorable = isIgnorable,
Ex = ex,
});
}
}
}
static ObjectValidator s_validator;
static void prepareValidator()
{
if (s_validator == null)
{
s_validator = new ObjectValidator();
}
}
public static JsonSchemaValidationException Validate(HashSet<string> required,
Dictionary<string, JsonSchema> properties,
JsonSchemaValidationContext c, T o)
{
prepareValidator();
return s_validator.Validate(required, properties, c, o);
}
internal static void ValidationResults(HashSet<string> required,
Dictionary<string, JsonSchema> properties,
JsonSchemaValidationContext c, T o,
Dictionary<string, ValidationResult> results)
{
prepareValidator();
s_validator.ValidationResults(required, properties, c, o, results);
}
}
public JsonSchemaValidationException Validate<T>(JsonSchemaValidationContext c, T o)
{
if (o == null)
{
return new JsonSchemaValidationException(c, "null");
}
if (Properties.Count < MinProperties)
{
return new JsonSchemaValidationException(c, "no properties");
}
return GenericValidator<T>.Validate(Required, Properties, c, o);
}
static class GenericSerializer<T>
{
class Serializer
{
delegate void FieldSerializer(JsonSchema s, JsonSchemaValidationContext c, IFormatter f, T o,
Dictionary<string, ValidationResult> vRes, string[] deps);
Dictionary<string, FieldSerializer> m_serializers;
static FieldSerializer CreateFieldSerializer(FieldInfo fi)
{
var mi = typeof(Serializer).GetMethod("_CreateFieldSerializer",
BindingFlags.Static | BindingFlags.NonPublic);
var g = mi.MakeGenericMethod(fi.FieldType);
return GenericInvokeCallFactory.StaticFunc<FieldInfo, FieldSerializer>(g)(fi);
}
static FieldSerializer _CreateFieldSerializer<U>(FieldInfo fi)
{
Func<T, U> getter = t =>
{
return (U)fi.GetValue(t);
};
return (s, c, f, o, vRes, deps) =>
{
var v = s.Validator;
var field = getter(o);
if (vRes[fi.Name].Ex != null)
{
return;
}
if (deps != null)
{
foreach(var dep in deps)
{
if (vRes[dep].Ex != null)
{
return;
}
}
}
f.Key(fi.Name);
v.Serialize(f, c, field);
};
}
public Serializer()
{
var serializers = new Dictionary<string, FieldSerializer>();
GenericFieldView<T>.CreateFieldProcessors<Serializer, FieldSerializer>(
CreateFieldSerializer, serializers);
m_serializers = serializers;
}
public void Serialize(JsonObjectValidator objectValidator,
IFormatter f, JsonSchemaValidationContext c, T o)
{
// Validates fields
var validationResults = new Dictionary<string, ValidationResult>();
GenericValidator<T>.ValidationResults(
objectValidator.Required, objectValidator.Properties,
c, o, validationResults);
// Serialize fields
f.BeginMap(objectValidator.Properties.Count());
foreach (var property in objectValidator.Properties)
{
var fieldName = property.Key;
var schema = property.Value;
string[] deps = null;
objectValidator.Dependencies.TryGetValue(fieldName, out deps);
FieldSerializer fs;
if (m_serializers.TryGetValue(fieldName, out fs))
{
fs(schema, c, f, o, validationResults, deps);
}
}
f.EndMap();
}
}
static FieldInfo[] s_fields;
static Serializer s_serializer;
public static void Serialize(JsonObjectValidator objectValidator,
IFormatter f, JsonSchemaValidationContext c, T value)
{
if (s_serializer == null)
{
s_serializer = new Serializer();
}
s_serializer.Serialize(objectValidator, f, c, value);
}
}
public void Serialize<T>(IFormatter f, JsonSchemaValidationContext c, T value)
{
GenericSerializer<T>.Serialize(this, f, c, value);
}
public static class GenericDeserializer<S, T>
where S : IListTreeItem, IValue<S>
{
delegate T Deserializer(ListTreeNode<S> src);
static Deserializer s_d;
delegate void FieldSetter(ListTreeNode<S> s, object o);
static FieldSetter GetFieldDeserializer<U>(FieldInfo fi)
{
return (s, o) =>
{
var u = default(U);
s.Deserialize(ref u);
fi.SetValue(o, u);
};
}
public static U DeserializeField<U>(JsonSchema prop, ListTreeNode<S> s)
{
var u = default(U);
prop.Validator.Deserialize(s, ref u);
return u;
}
public static void Deserialize(ListTreeNode<S> src, ref T dst, Dictionary<string, JsonSchema> props)
{
if (s_d == null)
{
var target = typeof(T);
var fields = target.GetFields(BindingFlags.Instance | BindingFlags.Public);
var fieldDeserializers = fields.ToDictionary(x => Utf8String.From(x.Name), x =>
{
/*
var mi = typeof(GenericDeserializer<T>).GetMethod("GetFieldDeserializer",
BindingFlags.Static | BindingFlags.NonPublic);
var g = mi.MakeGenericMethod(x.FieldType);
return (FieldSetter)g.Invoke(null, new object[] { x });
*/
JsonSchema prop;
if (!props.TryGetValue(x.Name, out prop))
{
return null;
}
var mi = typeof(GenericDeserializer<S, T>).GetMethod("DeserializeField",
BindingFlags.Static | BindingFlags.Public);
var g = mi.MakeGenericMethod(x.FieldType);
return (FieldSetter)((s, o) =>
{
var f = g.Invoke(null, new object[] { prop, s });
x.SetValue(o, f);
});
});
s_d = (ListTreeNode<S> s) =>
{
if (!s.IsMap())
{
throw new ArgumentException(s.Value.ValueType.ToString());
}
// boxing
var t = (object)Activator.CreateInstance<T>();
foreach (var kv in s.ObjectItems())
{
FieldSetter setter;
if (fieldDeserializers.TryGetValue(kv.Key.GetUtf8String(), out setter))
{
if (setter != null)
{
setter(kv.Value, t);
}
}
}
return (T)t;
};
}
dst = s_d(src);
}
}
public void Deserialize<T, U>(ListTreeNode<T> src, ref U dst)
where T : IListTreeItem, IValue<T>
{
GenericDeserializer<T, U>.Deserialize(src, ref dst, Properties);
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 1bdf39f36f58f584daee6d67f7ab446f
timeCreated: 1531812708
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,33 +0,0 @@
using System;
using System.Linq;
using System.Collections.Generic;
namespace UniJSON
{
[Flags]
public enum PropertyExportFlags
{
None,
PublicFields = 1,
PublicProperties = 2,
Default = PublicFields | PublicProperties,
}
public enum CompositionType
{
Unknown,
AllOf,
AnyOf,
OneOf,
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 9ff35fccc1467f341b052622fedcb3ca
timeCreated: 1531557083
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,320 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
#if UNIJSON_PROFILING
#else
using UnityEngine;
#endif
namespace UniJSON
{
public static class JsonSchemaValidatorFactory
{
struct JsonSchemaItem
{
public string Key;
public JsonSchema Schema;
public bool Required;
public string[] Dependencies;
}
static IEnumerable<JsonSchemaItem> GetProperties(Type t, PropertyExportFlags exportFlags)
{
// fields
foreach (var fi in t.GetFields())
{
var a = fi.GetCustomAttributes(typeof(JsonSchemaAttribute), true).FirstOrDefault() as JsonSchemaAttribute;
if (a == null)
{
a = fi.FieldType.GetCustomAttributes(typeof(JsonSchemaAttribute), true).FirstOrDefault() as JsonSchemaAttribute;
if (a == null)
{
// default
if (!fi.IsStatic && fi.IsPublic)
{
// only public instance field
a = new JsonSchemaAttribute();
}
}
}
// for array item
var ia = fi.GetCustomAttributes(typeof(ItemJsonSchemaAttribute), true).FirstOrDefault() as ItemJsonSchemaAttribute;
if (a == null)
{
//int x = 0;
}
else
{
yield return new JsonSchemaItem
{
Key = fi.Name,
Schema = JsonSchema.FromType(fi.FieldType, a, ia),
Required = a.Required,
Dependencies = a.Dependencies,
};
}
}
// properties
foreach (var pi in t.GetProperties())
{
var a = pi.GetCustomAttributes(typeof(JsonSchemaAttribute), true).FirstOrDefault() as JsonSchemaAttribute;
// for array item
var ia = pi.GetCustomAttributes(typeof(ItemJsonSchemaAttribute), true).FirstOrDefault() as ItemJsonSchemaAttribute;
if (a != null)
{
yield return new JsonSchemaItem
{
Key = pi.Name,
Schema = JsonSchema.FromType(pi.PropertyType, a, ia),
Required = a.Required,
Dependencies = a.Dependencies,
};
}
}
}
public static IJsonSchemaValidator Create(ValueNodeType valueType,
Type t = null,
BaseJsonSchemaAttribute a = null,
ItemJsonSchemaAttribute ia = null)
{
switch (valueType)
{
case ValueNodeType.Integer:
{
var v = new JsonIntValidator();
if (a != null)
{
if (!double.IsNaN(a.Minimum))
{
v.Minimum = (int)a.Minimum;
}
if (a.ExclusiveMinimum)
{
v.ExclusiveMinimum = a.ExclusiveMinimum;
}
if (!double.IsNaN(a.Maximum))
{
v.Maximum = (int)a.Maximum;
}
if (a.ExclusiveMaximum)
{
v.ExclusiveMaximum = a.ExclusiveMaximum;
}
if (a.MultipleOf != 0)
{
v.MultipleOf = (int)a.MultipleOf;
}
}
return v;
}
case ValueNodeType.Number:
{
var v = new JsonNumberValidator();
if (a != null)
{
if (!double.IsNaN(a.Minimum))
{
v.Minimum = (int)a.Minimum;
}
if (a.ExclusiveMinimum)
{
v.ExclusiveMinimum = a.ExclusiveMinimum;
}
if (!double.IsNaN(a.Maximum))
{
v.Maximum = (int)a.Maximum;
}
if (a.ExclusiveMaximum)
{
v.ExclusiveMaximum = a.ExclusiveMaximum;
}
if (a.MultipleOf != 0)
{
v.MultipleOf = (int)a.MultipleOf;
}
}
return v;
}
case ValueNodeType.String:
{
var v = new JsonStringValidator();
if (a != null)
{
if (a.Pattern != null)
{
v.Pattern = new System.Text.RegularExpressions.Regex(a.Pattern);
}
}
return v;
}
case ValueNodeType.Boolean:
return new JsonBoolValidator();
case ValueNodeType.Array:
{
var v = new JsonArrayValidator();
if (a != null)
{
if (a.MinItems != 0)
{
v.MinItems = a.MinItems;
}
if (a.MaxItems != 0)
{
v.MaxItems = a.MaxItems;
}
if (t != null)
{
if (ia == null)
{
ia = new ItemJsonSchemaAttribute();
}
Type elementType = null;
if (t.IsArray)
{
elementType = t.GetElementType();
}
else if (t.GetIsGenericList())
{
elementType = t.GetGenericArguments().First();
}
if (elementType != null)
{
/*
var sub = new JsonSchema
{
SkipComparison = ia.SkipSchemaComparison,
Validator = Create(elementType, ia, null)
};
*/
var sub = JsonSchema.FromType(elementType, ia, null);
v.Items = sub;
}
}
}
return v;
}
case ValueNodeType.Object:
{
if (t.GetIsGenericDictionary())
{
var genericFactory = typeof(JsonDictionaryValidator).GetMethod("Create", BindingFlags.Static | BindingFlags.Public);
var factory = genericFactory.MakeGenericMethod(t.GetGenericArguments()[1]);
var v = factory.Invoke(null, null) as IJsonSchemaValidator;
return v;
}
else
{
var v = new JsonObjectValidator();
if (a != null)
{
if (a.MinProperties > 0)
{
v.MinProperties = a.MinProperties;
}
// props
foreach (var prop in GetProperties(t, a.ExportFlags))
{
v.Properties.Add(prop.Key, prop.Schema);
if (prop.Required)
{
v.Required.Add(prop.Key);
}
if (prop.Dependencies != null)
{
v.Dependencies.Add(prop.Key, prop.Dependencies);
}
}
}
if (ia != null)
{
var sub = new JsonSchema
{
SkipComparison = ia.SkipSchemaComparison,
Validator = Create(typeof(object), ia, null)
};
v.AdditionalProperties = sub;
}
return v;
}
}
default:
throw new NotImplementedException();
}
}
public static IJsonSchemaValidator Create(string t)
{
return Create((ValueNodeType)Enum.Parse(typeof(ValueNodeType), t, true));
}
static Dictionary<Type, ValueNodeType> s_typeMap = new Dictionary<Type, ValueNodeType>
{
{typeof(byte), ValueNodeType.Integer },
{typeof(short), ValueNodeType.Integer },
{typeof(int), ValueNodeType.Integer },
{typeof(long), ValueNodeType.Integer },
{typeof(sbyte), ValueNodeType.Integer },
{typeof(ushort), ValueNodeType.Integer },
{typeof(uint), ValueNodeType.Integer },
{typeof(ulong), ValueNodeType.Integer },
{typeof(float), ValueNodeType.Number },
{typeof(double), ValueNodeType.Number },
{typeof(string), ValueNodeType.String },
{typeof(bool), ValueNodeType.Boolean },
// Unity types
{typeof(Vector3), ValueNodeType.Object },
};
static ValueNodeType ToJsonType(Type t)
{
ValueNodeType jsonValueType;
if (s_typeMap.TryGetValue(t, out jsonValueType))
{
return jsonValueType;
}
if (t.IsArray)
{
return ValueNodeType.Array;
}
if (t.GetIsGenericList())
{
return ValueNodeType.Array;
}
//if (t.IsClass)
{
return ValueNodeType.Object;
}
//throw new NotImplementedException(string.Format("No JsonType for {0}", t));
}
public static IJsonSchemaValidator Create(Type t, BaseJsonSchemaAttribute a, ItemJsonSchemaAttribute ia)
{
return Create(ToJsonType(t), t, a, ia);
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 9fef66d39a7b22b499bea68e0b22d000
timeCreated: 1531574156
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,143 +0,0 @@
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace UniJSON
{
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#string
/// </summary>
public class JsonStringValidator : IJsonSchemaValidator
{
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.3.1
/// </summary>
public int? MaxLength
{
get; set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.3.2
/// </summary>
public int? MinLength
{
get; set;
}
/// <summary>
/// http://json-schema.org/latest/json-schema-validation.html#rfc.section.6.3.3
/// </summary>
public Regex Pattern
{
get; set;
}
public override int GetHashCode()
{
return 4;
}
public override bool Equals(object obj)
{
var rhs = obj as JsonStringValidator;
if (rhs == null) return false;
if (MaxLength != rhs.MaxLength) return false;
if (MinLength != rhs.MinLength) return false;
if (Pattern == null && rhs.Pattern == null)
{
}
else if (Pattern == null)
{
return false;
}
else if (rhs.Pattern == null)
{
return false;
}
else if (Pattern.ToString() != rhs.Pattern.ToString())
{
return false;
}
return true;
}
public void Merge(IJsonSchemaValidator obj)
{
var rhs = obj as JsonStringValidator;
if (rhs == null)
{
throw new ArgumentException();
}
MaxLength = rhs.MaxLength;
MinLength = rhs.MinLength;
Pattern = rhs.Pattern;
}
public bool FromJsonSchema(IFileSystemAccessor fs, string key, ListTreeNode<JsonValue> value)
{
switch (key)
{
case "maxLength":
MaxLength = value.GetInt32();
return true;
case "minLength":
MinLength = value.GetInt32();
return true;
case "pattern":
Pattern = new Regex(value.GetString().Replace("\\\\", "\\"));
return true;
}
return false;
}
public void ToJsonSchema(IFormatter f)
{
f.Key("type"); f.Value("string");
}
public JsonSchemaValidationException Validate<T>(JsonSchemaValidationContext c, T o)
{
if (o == null)
{
return new JsonSchemaValidationException(c, "null");
}
var value = o as string;
if (MinLength.HasValue && value.Length < MinLength)
{
return new JsonSchemaValidationException(c, string.Format("minlength: {0}<{1}", value.Length, MinLength.Value));
}
if (MaxLength.HasValue && value.Length > MaxLength)
{
return new JsonSchemaValidationException(c, string.Format("maxlength: {0}>{1}", value.Length, MaxLength.Value));
}
if (Pattern != null && !Pattern.IsMatch(value))
{
return new JsonSchemaValidationException(c, string.Format("pattern: {0} not match {1}", Pattern, value));
}
return null;
}
public void Serialize<T>(IFormatter f, JsonSchemaValidationContext c, T o)
{
f.Value(GenericCast<T, string>.Cast(o));
}
public void Deserialize<T, U>(ListTreeNode<T> src, ref U dst)
where T: IListTreeItem, IValue<T>
{
dst = GenericCast<string, U>.Cast(src.GetString());
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 0256cc9f46a4e6744826cf5ca0aa1b46
timeCreated: 1531812574
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,17 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace UniJSON
{
public static class ListTreeNodeDeserializerExtensions
{
public static void Deserialize<T, U>(this ListTreeNode<T> self, ref U value)
where T : IListTreeItem, IValue<T>
{
GenericDeserializer<T, U>.Deserialize(self, ref value);
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 961c1bf9650027347a1279c4f04a1feb
timeCreated: 1545735557
licenseType: Pro
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -3,7 +3,7 @@
namespace UniJSON
{
public class MsgPackFormatter : IFormatter, IRpc
public class MsgPackFormatter : IFormatter
{
IStore m_store;
public MsgPackFormatter(IStore store)

View File

@@ -1,9 +0,0 @@
fileFormatVersion: 2
guid: e9f4765570f7add459493027e7057429
folderAsset: yes
timeCreated: 1543734557
licenseType: Free
DefaultImporter:
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,84 +0,0 @@
namespace UniJSON
{
public interface IRpc
{
void Request(Utf8String method);
void Request<A0>(Utf8String method, A0 a0);
void Request<A0, A1>(Utf8String method, A0 a0, A1 a1);
void Request<A0, A1, A2>(Utf8String method, A0 a0, A1 a1, A2 a2);
void Request<A0, A1, A2, A3>(Utf8String method, A0 a0, A1 a1, A2 a2, A3 a3);
void Request<A0, A1, A2, A3, A4>(Utf8String method, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4);
void Request<A0, A1, A2, A3, A4, A5>(Utf8String method, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5);
void ResponseSuccess(int id);
void ResponseSuccess<T>(int id, T result);
void ResponseError(int id, System.Exception error);
void Notify(Utf8String method);
void Notify<A0>(Utf8String method, A0 a0);
void Notify<A0, A1>(Utf8String method, A0 a0, A1 a1);
void Notify<A0, A1, A2>(Utf8String method, A0 a0, A1 a1, A2 a2);
void Notify<A0, A1, A2, A3>(Utf8String method, A0 a0, A1 a1, A2 a2, A3 a3);
void Notify<A0, A1, A2, A3, A4>(Utf8String method, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4);
void Notify<A0, A1, A2, A3, A4, A5>(Utf8String method, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5);
}
public static class RpcExtensions
{
public static void Request(this IRpc rpc, string method)
{
rpc.Request(Utf8String.From(method));
}
public static void Request<A0>(this IRpc rpc, string method, A0 a0)
{
rpc.Request(Utf8String.From(method), a0);
}
public static void Request<A0, A1>(this IRpc rpc, string method, A0 a0, A1 a1)
{
rpc.Request(Utf8String.From(method), a0, a1);
}
public static void Request<A0, A1, A2>(this IRpc rpc, string method, A0 a0, A1 a1, A2 a2)
{
rpc.Request(Utf8String.From(method), a0, a1, a2);
}
public static void Request<A0, A1, A2, A3>(this IRpc rpc, string method, A0 a0, A1 a1, A2 a2, A3 a3)
{
rpc.Request(Utf8String.From(method), a0, a1, a2, a3);
}
public static void Request<A0, A1, A2, A3, A4>(this IRpc rpc, string method, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4)
{
rpc.Request(Utf8String.From(method), a0, a1, a2, a3, a4);
}
public static void Request<A0, A1, A2, A3, A4, A5>(this IRpc rpc, string method, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5)
{
rpc.Request(Utf8String.From(method), a0, a1, a2, a3, a4, a5);
}
public static void Notify(this IRpc rpc, string method)
{
rpc.Notify(Utf8String.From(method));
}
public static void Notify<A0>(this IRpc rpc, string method, A0 a0)
{
rpc.Notify(Utf8String.From(method), a0);
}
public static void Notify<A0, A1>(this IRpc rpc, string method, A0 a0, A1 a1)
{
rpc.Notify(Utf8String.From(method), a0, a1);
}
public static void Notify<A0, A1, A2>(this IRpc rpc, string method, A0 a0, A1 a1, A2 a2)
{
rpc.Notify(Utf8String.From(method), a0, a1, a2);
}
public static void Notify<A0, A1, A2, A3>(this IRpc rpc, string method, A0 a0, A1 a1, A2 a2, A3 a3)
{
rpc.Notify(Utf8String.From(method), a0, a1, a2, a3);
}
public static void Notify<A0, A1, A2, A3, A4>(this IRpc rpc, string method, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4)
{
rpc.Notify(Utf8String.From(method), a0, a1, a2, a3, a4);
}
public static void Notify<A0, A1, A2, A3, A4, A5>(this IRpc rpc, string method, A0 a0, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5)
{
rpc.Notify(Utf8String.From(method), a0, a1, a2, a3, a4, a5);
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 565cc7f9a76689a45b352370db24f90f
timeCreated: 1543734576
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -1,80 +0,0 @@
using System;
using System.Collections.Generic;
namespace UniJSON
{
public class RpcDispatcher<T>
where T : IListTreeItem, IValue<T>
{
delegate void Callback(int id, ListTreeNode<T> args, IRpc f);
Dictionary<string, Callback> m_map = new Dictionary<string, Callback>();
#region Action
public void Register<A0>(string method, Action<A0> action)
{
m_map.Add(method, (id, args, f) =>
{
var it = args.ArrayItems().GetEnumerator();
var a0 = default(A0);
it.MoveNext();
it.Current.Deserialize(ref a0);
try
{
action(a0);
f.ResponseSuccess(id);
}
catch(Exception ex)
{
f.ResponseError(id, ex);
}
});
}
public void Register<A0, A1>(string method, Action<A0, A1> action)
{
throw new NotImplementedException();
}
#endregion
#region Func
public void Register<A0, A1, R>(string method, Func<A0, A1, R> action)
{
m_map.Add(method, (id, args, f) =>
{
var it = args.ArrayItems().GetEnumerator();
var a0 = default(A0);
it.MoveNext();
it.Current.Deserialize(ref a0);
var a1 = default(A1);
it.MoveNext();
it.Current.Deserialize(ref a1);
try
{
var r = action(a0, a1);
f.ResponseSuccess(id, r);
}
catch(Exception ex)
{
f.ResponseError(id, ex);
}
});
}
#endregion
public void Call(IRpc f, int id, string method, ListTreeNode<T> args)
{
Callback callback;
if (!m_map.TryGetValue(method, out callback))
{
throw new KeyNotFoundException();
}
callback(id, args, f);
}
}
}

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 648f9a3ef9c1a6f41b11198b1f499d5c
timeCreated: 1543549119
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -156,13 +156,6 @@ namespace VRM
var json = model.ToJson();
Assert.AreEqual(@"{}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_MaterialValueBind>().Serialize(model, c);
Assert.AreEqual(json, json2);
}
[Test]
@@ -178,28 +171,12 @@ namespace VRM
var json = model.ToJson();
Assert.AreEqual(@"{""mesh"":1,""index"":3,""weight"":2}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_BlendShapeBind>().Serialize(model, c);
Assert.AreEqual(json, json2);
}
[Test]
public void BlendShapeBindTestError()
{
var model = new glTF_VRM_BlendShapeBind();
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_BlendShapeBind>().Serialize(model, c)
);
Assert.AreEqual("[mesh.String] minimum: ! -1>=0", ex.Message);
}
[Test]
@@ -211,15 +188,8 @@ namespace VRM
};
var json = model.ToJson();
Assert.AreEqual(@"{""presetName"":""neutral"",""isBinary"":false,""binds"":[],""materialValues"":[]}", json);
Assert.AreEqual(@"{""presetName"":""neutral"",""binds"":[],""materialValues"":[],""isBinary"":false}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_BlendShapeGroup>().Serialize(model, c);
Assert.AreEqual(@"{""presetName"":""neutral"",""binds"":[],""materialValues"":[],""isBinary"":false}", json2);
}
[Test]
@@ -229,15 +199,6 @@ namespace VRM
{
presetName = "aaaaaaaaaaaa_not_exists_",
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_BlendShapeGroup>().Serialize(model, c)
);
Assert.AreEqual("[presetName.String] aaaaaaaaaaaa_not_exists_ is not valid enum", ex.Message);
}
[Test]
@@ -248,13 +209,6 @@ namespace VRM
var json = model.ToJson();
Assert.AreEqual(@"{""xRange"":90,""yRange"":10}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_DegreeMap>().Serialize(model, c);
Assert.AreEqual(json, json2);
}
[Test]
@@ -265,13 +219,6 @@ namespace VRM
var json = model.ToJson();
Assert.AreEqual(@"{""mesh"":0}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_MeshAnnotation>().Serialize(model, c);
Assert.AreEqual(json, json2);
}
[Test]
@@ -284,15 +231,6 @@ namespace VRM
@"{""firstPersonBone"":-1,""firstPersonBoneOffset"":{""x"":0,""y"":0,""z"":0},""meshAnnotations"":[],""lookAtTypeName"":""Bone"",""lookAtHorizontalInner"":{""xRange"":90,""yRange"":10},""lookAtHorizontalOuter"":{""xRange"":90,""yRange"":10},""lookAtVerticalDown"":{""xRange"":90,""yRange"":10},""lookAtVerticalUp"":{""xRange"":90,""yRange"":10}}",
json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_Firstperson>().Serialize(model, c);
Assert.AreEqual(
@"{""firstPersonBoneOffset"":{""x"":0,""y"":0,""z"":0},""meshAnnotations"":[],""lookAtTypeName"":""Bone"",""lookAtHorizontalInner"":{""xRange"":90,""yRange"":10},""lookAtHorizontalOuter"":{""xRange"":90,""yRange"":10},""lookAtVerticalDown"":{""xRange"":90,""yRange"":10},""lookAtVerticalUp"":{""xRange"":90,""yRange"":10}}",
json2);
}
[Test]
@@ -307,16 +245,6 @@ namespace VRM
var json = model.ToJson();
Assert.AreEqual(@"{""bone"":""hips"",""node"":0,""useDefaultValues"":true}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_HumanoidBone>().Serialize(model, c);
// NOTE: New serializer outputs values which will not be used...
Assert.AreEqual(
@"{""bone"":""hips"",""node"":0,""useDefaultValues"":true,""min"":{""x"":0,""y"":0,""z"":0},""max"":{""x"":0,""y"":0,""z"":0},""center"":{""x"":0,""y"":0,""z"":0},""axisLength"":0}",
json2);
}
[Test]
@@ -326,15 +254,6 @@ namespace VRM
{
bone = "hips", // NOTE: This field must not be null?
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_HumanoidBone>().Serialize(model, c)
);
Assert.AreEqual("[node.String] minimum: ! -1>=0", ex.Message);
}
[Test]
@@ -345,14 +264,6 @@ namespace VRM
var json = model.ToJson();
Assert.AreEqual(@"{""humanBones"":[],""armStretch"":0.05,""legStretch"":0.05,""upperArmTwist"":0.5,""lowerArmTwist"":0.5,""upperLegTwist"":0.5,""lowerLegTwist"":0.5,""feetSpacing"":0,""hasTranslationDoF"":false}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_Humanoid>().Serialize(model, c);
// NOTE: New serializer outputs values which will not be used...
Assert.AreEqual(json, json2);
}
[Test]
@@ -385,19 +296,6 @@ namespace VRM
var json = model.ToJson();
Assert.AreEqual(@"{""renderQueue"":-1,""floatProperties"":{""float"":1},""vectorProperties"":{""vector"":[0,1,2,3]},""textureProperties"":{""texture"":0},""keywordMap"":{""keyword"":true},""tagMap"":{""tag"":""map""}}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_Material>().Serialize(model, c);
// NOTE: New serializer outputs values which will not be used...
Assert.AreEqual(json, json2);
// deserialize
var deserialized = default(glTF_VRM_Material);
json.ParseAsJson().Deserialize(ref deserialized);
Assert.AreEqual(1, deserialized.floatProperties.Count);
}
[Test]
@@ -415,14 +313,6 @@ namespace VRM
var json = model.ToJson();
Assert.AreEqual(@"{""texture"":-1,""allowedUserName"":""OnlyAuthor"",""violentUssageName"":""Disallow"",""sexualUssageName"":""Disallow"",""commercialUssageName"":""Disallow"",""licenseName"":""CC0""}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_Meta>().Serialize(model, c);
// NOTE: New serializer outputs values which will not be used...
Assert.AreEqual(@"{""allowedUserName"":""OnlyAuthor"",""violentUssageName"":""Disallow"",""sexualUssageName"":""Disallow"",""commercialUssageName"":""Disallow"",""licenseName"":""CC0""}", json2);
}
[Test]
@@ -436,15 +326,6 @@ namespace VRM
sexualUssageName = null,
commercialUssageName = null,
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_Meta>().Serialize(model, c)
);
Assert.AreEqual("[allowedUserName.String] null", ex.Message);
}
{
@@ -457,15 +338,6 @@ namespace VRM
//licenseName = "CC0",
licenseName = null,
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_Meta>().Serialize(model, c)
);
Assert.AreEqual("[licenseName.String] null", ex.Message);
}
{
@@ -477,15 +349,6 @@ namespace VRM
commercialUssageName = "Disallow",
licenseName = "_INVALID_SOME_THING_",
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_Meta>().Serialize(model, c)
);
Assert.AreEqual("[licenseName.String] _INVALID_SOME_THING_ is not valid enum", ex.Message);
}
{
@@ -498,15 +361,6 @@ namespace VRM
commercialUssageName = "Disallow",
licenseName = "CC0",
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_Meta>().Serialize(model, c)
);
Assert.AreEqual("[allowedUserName.String] null", ex.Message);
}
{
@@ -518,15 +372,6 @@ namespace VRM
commercialUssageName = "Disallow",
licenseName = "CC0",
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_Meta>().Serialize(model, c)
);
Assert.AreEqual("[allowedUserName.String] _INVALID_SOME_THING_ is not valid enum", ex.Message);
}
{
@@ -539,15 +384,6 @@ namespace VRM
commercialUssageName = "Disallow",
licenseName = "CC0",
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_Meta>().Serialize(model, c)
);
Assert.AreEqual("[violentUssageName.String] null", ex.Message);
}
{
@@ -559,15 +395,6 @@ namespace VRM
commercialUssageName = "Disallow",
licenseName = "CC0",
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_Meta>().Serialize(model, c)
);
Assert.AreEqual("[violentUssageName.String] _INVALID_SOME_THING_ is not valid enum", ex.Message);
}
{
@@ -580,15 +407,6 @@ namespace VRM
commercialUssageName = "Disallow",
licenseName = "CC0",
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_Meta>().Serialize(model, c)
);
Assert.AreEqual("[sexualUssageName.String] null", ex.Message);
}
{
@@ -600,15 +418,6 @@ namespace VRM
commercialUssageName = "Disallow",
licenseName = "CC0",
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_Meta>().Serialize(model, c)
);
Assert.AreEqual("[sexualUssageName.String] _INVALID_SOME_THING_ is not valid enum", ex.Message);
}
{
@@ -621,15 +430,6 @@ namespace VRM
commercialUssageName = null,
licenseName = "CC0",
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_Meta>().Serialize(model, c)
);
Assert.AreEqual("[commercialUssageName.String] null", ex.Message);
}
{
@@ -641,15 +441,6 @@ namespace VRM
commercialUssageName = "_INVALID_SOME_THING_",
licenseName = "CC0",
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_Meta>().Serialize(model, c)
);
Assert.AreEqual("[commercialUssageName.String] _INVALID_SOME_THING_ is not valid enum", ex.Message);
}
}
@@ -676,14 +467,6 @@ namespace VRM
var json = model.ToJson();
Assert.AreEqual(@"{""offset"":{""x"":1,""y"":2,""z"":3},""radius"":42}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_SecondaryAnimationCollider>().Serialize(model, c);
// NOTE: New serializer outputs values which will not be used...
Assert.AreEqual(json, json2);
}
[Test]
@@ -694,14 +477,6 @@ namespace VRM
var json = model.ToJson();
Assert.AreEqual(@"{""node"":0,""colliders"":[]}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_SecondaryAnimationColliderGroup>().Serialize(model, c);
// NOTE: New serializer outputs values which will not be used...
Assert.AreEqual(json, json2);
}
[Test]
@@ -711,15 +486,6 @@ namespace VRM
{
node = -1,
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_SecondaryAnimationColliderGroup>().Serialize(model, c)
);
Assert.AreEqual("[node.String] minimum: ! -1>=0", ex.Message);
}
[Test]
@@ -730,14 +496,6 @@ namespace VRM
var json = model.ToJson();
Assert.AreEqual(@"{""stiffiness"":0,""gravityPower"":0,""gravityDir"":{""x"":0,""y"":0,""z"":0},""dragForce"":0,""center"":0,""hitRadius"":0,""bones"":[],""colliderGroups"":[]}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_SecondaryAnimationGroup>().Serialize(model, c);
// NOTE: New serializer outputs values which will not be used...
Assert.AreEqual(json, json2);
}
[Test]
@@ -747,15 +505,6 @@ namespace VRM
{
bones = new int[] { -1 }
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_SecondaryAnimationGroup>().Serialize(model, c)
);
Assert.AreEqual("[bones.String] minimum: ! -1>=0", ex.Message);
}
[Test]
@@ -765,15 +514,6 @@ namespace VRM
{
colliderGroups = new int[] { -1 }
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var ex = Assert.Throws<JsonSchemaValidationException>(
() => JsonSchema.FromType<glTF_VRM_SecondaryAnimationGroup>().Serialize(model, c)
);
Assert.AreEqual("[colliderGroups.String] minimum: ! -1>=0", ex.Message);
}
[Test]
@@ -784,14 +524,6 @@ namespace VRM
var json = model.ToJson();
Assert.AreEqual(@"{""boneGroups"":[],""colliderGroups"":[]}", json);
Debug.Log(json);
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_SecondaryAnimation>().Serialize(model, c);
// NOTE: New serializer outputs values which will not be used...
Assert.AreEqual(json, json2);
}
[Test]
@@ -806,15 +538,6 @@ namespace VRM
secondaryAnimation = null,
materialProperties = null,
};
var c = new JsonSchemaValidationContext("")
{
EnableDiagnosisForNotRequiredFields = true,
};
var json2 = JsonSchema.FromType<glTF_VRM_extensions>().Serialize(model, c);
var expected =
String.Format(@"{{""exporterVersion"":""{0}"",""specVersion"":""0.0""}}", VRMVersion.VRM_VERSION);
Assert.AreEqual(expected, json2);
}
// TODO: Move to another suitable location

File diff suppressed because it is too large Load Diff

View File

@@ -1,12 +0,0 @@
fileFormatVersion: 2
guid: 7e3d4b1fe26c7984f93ae501382f2dd6
timeCreated: 1550041070
licenseType: Free
MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:

View File

@@ -89,17 +89,6 @@ namespace VRM
void LoadMeta()
{
var meta = ReadMeta();
if (meta.Thumbnail == null)
{
/*
// 作る
var lookAt = Root.GetComponent<VRMLookAtHead>();
var thumbnail = lookAt.CreateThumbnail();
thumbnail.name = "thumbnail";
meta.Thumbnail = thumbnail;
Textures.Add(new TextureItem(thumbnail));
*/
}
var _meta = Root.AddComponent<VRMMeta>();
_meta.Meta = meta;
Meta = meta;