2 // Copyright (c) 2007 James Newton-King
4 // Permission is hereby granted, free of charge, to any person
5 // obtaining a copy of this software and associated documentation
6 // files (the "Software"), to deal in the Software without
7 // restriction, including without limitation the rights to use,
8 // copy, modify, merge, publish, distribute, sublicense, and/or sell
9 // copies of the Software, and to permit persons to whom the
10 // Software is furnished to do so, subject to the following
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
18 // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
20 // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
21 // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23 // OTHER DEALINGS IN THE SOFTWARE.
27 using System.Collections.Generic;
30 using System.Globalization;
31 using Newtonsoft.Json.Utilities;
32 using Newtonsoft.Json.Linq;
34 namespace Newtonsoft.Json.Schema
36 internal class JsonSchemaBuilder
38 private JsonReader _reader;
39 private readonly IList<JsonSchema> _stack;
40 private readonly JsonSchemaResolver _resolver;
41 private JsonSchema _currentSchema;
43 private void Push(JsonSchema value)
45 _currentSchema = value;
47 _resolver.LoadedSchemas.Add(value);
50 private JsonSchema Pop()
52 JsonSchema poppedSchema = _currentSchema;
53 _stack.RemoveAt(_stack.Count - 1);
54 _currentSchema = _stack.LastOrDefault();
59 private JsonSchema CurrentSchema
61 get { return _currentSchema; }
64 public JsonSchemaBuilder(JsonSchemaResolver resolver)
66 _stack = new List<JsonSchema>();
70 internal JsonSchema Parse(JsonReader reader)
74 if (reader.TokenType == JsonToken.None)
80 private JsonSchema BuildSchema()
82 if (_reader.TokenType != JsonToken.StartObject)
83 throw new Exception("Expected StartObject while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
86 // empty schema object
87 if (_reader.TokenType == JsonToken.EndObject)
89 Push(new JsonSchema());
93 string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
97 if (propertyName == JsonSchemaConstants.ReferencePropertyName)
99 string id = (string)_reader.Value;
101 JsonSchema referencedSchema = _resolver.GetSchema(id);
102 if (referencedSchema == null)
103 throw new Exception("Could not resolve schema reference for Id '{0}'.".FormatWith(CultureInfo.InvariantCulture, id));
105 return referencedSchema;
108 // regular ol' schema object
109 Push(new JsonSchema());
111 ProcessSchemaProperty(propertyName);
113 while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
115 propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
118 ProcessSchemaProperty(propertyName);
124 private void ProcessSchemaProperty(string propertyName)
126 switch (propertyName)
128 case JsonSchemaConstants.TypePropertyName:
129 CurrentSchema.Type = ProcessType();
131 case JsonSchemaConstants.IdPropertyName:
132 CurrentSchema.Id = (string) _reader.Value;
134 case JsonSchemaConstants.TitlePropertyName:
135 CurrentSchema.Title = (string) _reader.Value;
137 case JsonSchemaConstants.DescriptionPropertyName:
138 CurrentSchema.Description = (string)_reader.Value;
140 case JsonSchemaConstants.PropertiesPropertyName:
143 case JsonSchemaConstants.ItemsPropertyName:
146 case JsonSchemaConstants.AdditionalPropertiesPropertyName:
147 ProcessAdditionalProperties();
149 case JsonSchemaConstants.PatternPropertiesPropertyName:
150 ProcessPatternProperties();
152 case JsonSchemaConstants.RequiredPropertyName:
153 CurrentSchema.Required = (bool)_reader.Value;
155 case JsonSchemaConstants.RequiresPropertyName:
156 CurrentSchema.Requires = (string) _reader.Value;
158 case JsonSchemaConstants.IdentityPropertyName:
161 case JsonSchemaConstants.MinimumPropertyName:
162 CurrentSchema.Minimum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
164 case JsonSchemaConstants.MaximumPropertyName:
165 CurrentSchema.Maximum = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
167 case JsonSchemaConstants.ExclusiveMinimumPropertyName:
168 CurrentSchema.ExclusiveMinimum = (bool)_reader.Value;
170 case JsonSchemaConstants.ExclusiveMaximumPropertyName:
171 CurrentSchema.ExclusiveMaximum = (bool)_reader.Value;
173 case JsonSchemaConstants.MaximumLengthPropertyName:
174 CurrentSchema.MaximumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
176 case JsonSchemaConstants.MinimumLengthPropertyName:
177 CurrentSchema.MinimumLength = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
179 case JsonSchemaConstants.MaximumItemsPropertyName:
180 CurrentSchema.MaximumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
182 case JsonSchemaConstants.MinimumItemsPropertyName:
183 CurrentSchema.MinimumItems = Convert.ToInt32(_reader.Value, CultureInfo.InvariantCulture);
185 case JsonSchemaConstants.DivisibleByPropertyName:
186 CurrentSchema.DivisibleBy = Convert.ToDouble(_reader.Value, CultureInfo.InvariantCulture);
188 case JsonSchemaConstants.DisallowPropertyName:
189 CurrentSchema.Disallow = ProcessType();
191 case JsonSchemaConstants.DefaultPropertyName:
194 case JsonSchemaConstants.HiddenPropertyName:
195 CurrentSchema.Hidden = (bool) _reader.Value;
197 case JsonSchemaConstants.ReadOnlyPropertyName:
198 CurrentSchema.ReadOnly = (bool) _reader.Value;
200 case JsonSchemaConstants.FormatPropertyName:
201 CurrentSchema.Format = (string) _reader.Value;
203 case JsonSchemaConstants.PatternPropertyName:
204 CurrentSchema.Pattern = (string) _reader.Value;
206 case JsonSchemaConstants.OptionsPropertyName:
209 case JsonSchemaConstants.EnumPropertyName:
212 case JsonSchemaConstants.ExtendsPropertyName:
221 private void ProcessExtends()
223 CurrentSchema.Extends = BuildSchema();
226 private void ProcessEnum()
228 if (_reader.TokenType != JsonToken.StartArray)
229 throw new Exception("Expected StartArray token while parsing enum values, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
231 CurrentSchema.Enum = new List<JToken>();
233 while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
235 JToken value = JToken.ReadFrom(_reader);
236 CurrentSchema.Enum.Add(value);
240 private void ProcessOptions()
242 CurrentSchema.Options = new Dictionary<JToken, string>(new JTokenEqualityComparer());
244 switch (_reader.TokenType)
246 case JsonToken.StartArray:
247 while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
249 if (_reader.TokenType != JsonToken.StartObject)
250 throw new Exception("Expect object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
255 while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
257 string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
260 switch (propertyName)
262 case JsonSchemaConstants.OptionValuePropertyName:
263 value = JToken.ReadFrom(_reader);
265 case JsonSchemaConstants.OptionLabelPropertyName:
266 label = (string) _reader.Value;
269 throw new Exception("Unexpected property in JSON schema option: {0}.".FormatWith(CultureInfo.InvariantCulture, propertyName));
274 throw new Exception("No value specified for JSON schema option.");
276 if (CurrentSchema.Options.ContainsKey(value))
277 throw new Exception("Duplicate value in JSON schema option collection: {0}".FormatWith(CultureInfo.InvariantCulture, value));
279 CurrentSchema.Options.Add(value, label);
283 throw new Exception("Expected array token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
287 private void ProcessDefault()
289 CurrentSchema.Default = JToken.ReadFrom(_reader);
292 private void ProcessIdentity()
294 CurrentSchema.Identity = new List<string>();
296 switch (_reader.TokenType)
298 case JsonToken.String:
299 CurrentSchema.Identity.Add(_reader.Value.ToString());
301 case JsonToken.StartArray:
302 while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
304 if (_reader.TokenType != JsonToken.String)
305 throw new Exception("Exception JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
307 CurrentSchema.Identity.Add(_reader.Value.ToString());
311 throw new Exception("Expected array or JSON property name string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
315 private void ProcessAdditionalProperties()
317 if (_reader.TokenType == JsonToken.Boolean)
318 CurrentSchema.AllowAdditionalProperties = (bool)_reader.Value;
320 CurrentSchema.AdditionalProperties = BuildSchema();
323 private void ProcessPatternProperties()
325 Dictionary<string, JsonSchema> patternProperties = new Dictionary<string, JsonSchema>();
327 if (_reader.TokenType != JsonToken.StartObject)
328 throw new Exception("Expected start object token.");
330 while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
332 string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
335 if (patternProperties.ContainsKey(propertyName))
336 throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName));
338 patternProperties.Add(propertyName, BuildSchema());
341 CurrentSchema.PatternProperties = patternProperties;
344 private void ProcessItems()
346 CurrentSchema.Items = new List<JsonSchema>();
348 switch (_reader.TokenType)
350 case JsonToken.StartObject:
351 CurrentSchema.Items.Add(BuildSchema());
353 case JsonToken.StartArray:
354 while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
356 CurrentSchema.Items.Add(BuildSchema());
360 throw new Exception("Expected array or JSON schema object token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
364 private void ProcessProperties()
366 IDictionary<string, JsonSchema> properties = new Dictionary<string, JsonSchema>();
368 if (_reader.TokenType != JsonToken.StartObject)
369 throw new Exception("Expected StartObject token while parsing schema properties, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
371 while (_reader.Read() && _reader.TokenType != JsonToken.EndObject)
373 string propertyName = Convert.ToString(_reader.Value, CultureInfo.InvariantCulture);
376 if (properties.ContainsKey(propertyName))
377 throw new Exception("Property {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, propertyName));
379 properties.Add(propertyName, BuildSchema());
382 CurrentSchema.Properties = properties;
385 private JsonSchemaType? ProcessType()
387 switch (_reader.TokenType)
389 case JsonToken.String:
390 return MapType(_reader.Value.ToString());
391 case JsonToken.StartArray:
392 // ensure type is in blank state before ORing values
393 JsonSchemaType? type = JsonSchemaType.None;
395 while (_reader.Read() && _reader.TokenType != JsonToken.EndArray)
397 if (_reader.TokenType != JsonToken.String)
398 throw new Exception("Exception JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
400 type = type | MapType(_reader.Value.ToString());
405 throw new Exception("Expected array or JSON schema type string token, got {0}.".FormatWith(CultureInfo.InvariantCulture, _reader.TokenType));
409 internal static JsonSchemaType MapType(string type)
411 JsonSchemaType mappedType;
412 if (!JsonSchemaConstants.JsonSchemaTypeMapping.TryGetValue(type, out mappedType))
413 throw new Exception("Invalid JSON schema type: {0}".FormatWith(CultureInfo.InvariantCulture, type));
418 internal static string MapType(JsonSchemaType type)
420 return JsonSchemaConstants.JsonSchemaTypeMapping.Single(kv => kv.Value == type).Key;