public void Serialize <TModel>(TModel model, Stream outputStream, Action <JsonSerializerSettings> settings, bool minify = false) where TModel : class { // Write to stream directly using the custom JSON writer without closing the stream TextWriter textWriter = new StreamWriter(outputStream); using (DescriptiveJsonWriter writer = new DescriptiveJsonWriter(textWriter)) { writer.Minify = minify; // Setup JSON Settings JsonSerializerSettings jsonSettings = JsonApi.CloneSettings(this._jsonSettings); settings?.Invoke(jsonSettings); // Serialize JsonSerializer.CreateDefault(jsonSettings).Serialize(writer, model); writer.Flush(); } }
private void WriteObject(object value, JObject token, DescriptiveJsonWriter writer, JsonSerializer serializer) { Dictionary <string, string> descriptions = new Dictionary <string, string>(); Dictionary <string, object> childrenValues = new Dictionary <string, object>(); // Get all the property descriptions foreach (PropertyInfo property in value.GetType().GetProperties()) { this.GetMemberData(property, property.GetValue(value), childrenValues, descriptions); } // Get all the field descriptions foreach (FieldInfo field in value.GetType().GetFields()) { this.GetMemberData(field, field.GetValue(value), childrenValues, descriptions); } // Write the object writer.WriteStartObject(); foreach ((string property, JToken valueToken) in (IDictionary <string, JToken>)token) { // Write the property's description if (descriptions.TryGetValue(property, out string description)) { writer.WritePropertyComment(description); } // Write the property's name writer.WritePropertyName(property); if (childrenValues.TryGetValue(property, out object childValue)) { // Write the child object serializer.Serialize(writer, childValue); } else { // Write the value valueToken.WriteTo(writer, serializer.Converters.ToArray()); } } writer.WriteEndObject(); }