-
Notifications
You must be signed in to change notification settings - Fork 748
Expand file tree
/
Copy pathMetadataStringOrArrayStjConverter.cs
More file actions
42 lines (37 loc) · 1.74 KB
/
MetadataStringOrArrayStjConverter.cs
File metadata and controls
42 lines (37 loc) · 1.74 KB
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
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace NuGet.Protocol.Converters
{
/// <summary>
/// Reads a JSON string or array of strings into an <see cref="IReadOnlyList{T}"/> of strings.
/// Equivalent to <see cref="MetadataStringOrArrayConverter"/> for System.Text.Json.
/// </summary>
/// <remarks>NSJ equivalent: <see cref="MetadataStringOrArrayConverter"/>.</remarks>
internal sealed class MetadataStringOrArrayStjConverter : JsonConverter<IReadOnlyList<string>>
{
public override IReadOnlyList<string>? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.String)
{
var str = reader.GetString();
return string.IsNullOrWhiteSpace(str) ? null : new[] { str! };
}
if (reader.TokenType != JsonTokenType.StartArray)
{
throw new JsonException(string.Format(System.Globalization.CultureInfo.CurrentCulture, Strings.Error_UnexpectedJsonToken, reader.TokenType));
}
var values = new List<string>();
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
{
values.Add(reader.GetString() ?? string.Empty);
}
return values.ToArray();
}
public override void Write(Utf8JsonWriter writer, IReadOnlyList<string> value, JsonSerializerOptions options)
=> throw new NotSupportedException();
}
}