-
Notifications
You must be signed in to change notification settings - Fork 368
/
JsonFormatter{T}.cs
47 lines (37 loc) · 1.19 KB
/
JsonFormatter{T}.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Text.Json;
namespace Microsoft.DotNet.Interactive.Formatting;
public class JsonFormatter<T> : TypeFormatter<T>
{
private readonly FormatDelegate<T> _format;
public override bool Format(T instance, FormatContext context)
{
return _format(instance, context);
}
public JsonFormatter()
{
_format = FormatInstance;
bool FormatInstance(T instance, FormatContext context)
{
var json = JsonSerializer.Serialize(instance, JsonFormatter.SerializerOptions);
context.Writer.Write(json);
return true;
}
}
public JsonFormatter(FormatDelegate<T> format)
{
_format = format;
}
public JsonFormatter(Action<T, FormatContext> format)
{
_format = FormatInstance;
bool FormatInstance(T instance, FormatContext context)
{
format(instance, context);
return true;
}
}
public override string MimeType { get; } = JsonFormatter.MimeType;
}