public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.StartObject) { throw new Exception("Template variable does not start with StartObject"); } var startDepth = reader.Depth; var startPath = reader.Path; reader.Read(); //skip $type if (reader.TokenType == JsonToken.PropertyName && (string)reader.Value == "$type") { reader.Read(); reader.Read(); } //skip Type property name reader.Read(); var templateVariable = new TemplateVariable(); var type = serializer.SerializationBinder.BindToType("", (string)reader.Value); templateVariable.Type = type; reader.Read(); if (reader.TokenType != JsonToken.EndObject) { reader.Read(); if (typeof(IDef).IsAssignableFrom(type)) { templateVariable.Type = typeof(DefRef <>).MakeGenericType(typeof(BaseDef)); if (reader.TokenType != JsonToken.Null) { templateVariable.Value = serializer.Deserialize(reader, typeof(DefRef <>).MakeGenericType(type)); } else { templateVariable.Value = null; } } else { templateVariable.Type = type; templateVariable.Value = serializer.Deserialize(reader, templateVariable.Type); } //read last token of value reader.Read(); } var endDepth = reader.Depth; if (endDepth != startDepth) { throw new Exception($"Depth is different in tempVarConverter {startPath} {startDepth} {endDepth} {type.Name}"); } return(templateVariable); }
public void SetVar(string var, TemplateVariable obj) { if (!IsProto) { LoadingFrames.Peek().RootTemplateFrame.Variables.Add(var, obj); return; } if (ProtoStack.Last(x => x.IsProtoLoading).Variables.ContainsKey(var)) { //do nothing, except check the type var checkedAgainstType = ProtoStack.Last(x => x.IsProtoLoading).Variables[var].Type; if (checkedAgainstType.IsGenericType && checkedAgainstType.GetGenericTypeDefinition() == typeof(DefRef <>)) { return;//do nothing, we can't yet check this stuff in a meaningfull manner } if (!obj.Type.IsAssignableFrom(checkedAgainstType) && !PrimitiveTypesConverter.CanConvert(checkedAgainstType, obj.Type)) { throw new Exception($"Type mismatch in template variables {ProtoStack.Peek().Variables[var].VariableId} {checkedAgainstType.Name} {obj.Type.Name} {obj.VariableId} {obj.Type?.Name}"); } return; } ProtoStack.Last(x => x.IsProtoLoading).Variables.Add(var, obj); }