Exemple #1
0
        /// <summary>
        ///		Asynchronously serialise data to an output stream.
        /// </summary>
        /// <param name="context">
        ///		Contextual information about the data being deserialised.
        /// </param>
        /// <param name="stream">
        ///		The output stream to which the serialised data will be written.
        /// </param>
        /// <returns>
        ///		A <see cref="Task"/> representing the asynchronous operation.
        /// </returns>
        public Task WriteAsync(OutputFormatterContext context, Stream stream)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (stream == null)
            {
                throw new ArgumentNullException(nameof(stream));
            }

            if (!SupportedMediaTypes.Contains(context.MediaType))
            {
                throw new NotSupportedException($"The {nameof(JsonFormatter)} cannot write content of type '{context.MediaType}'.");
            }

            using (TextWriter writer = context.CreateWriter(stream))
            {
                JsonSerializer serializer = JsonSerializer.Create(SerializerSettings);
                serializer.Serialize(writer, context.Data, context.DataType);
            }

            return(Task.CompletedTask);
        }