修复ArrayString错误

This commit is contained in:
falcon 2022-05-25 09:19:38 +08:00
parent 3ef1ea6199
commit df23896b4d
2 changed files with 30 additions and 5 deletions

View File

@ -1,4 +1,5 @@
using System; using System;
using System.Collections.Generic;
using System.Text.Json; using System.Text.Json;
using System.Text.Json.Serialization; using System.Text.Json.Serialization;
@ -16,15 +17,30 @@ namespace Falcon.SugarApi.JsonSerialize
/// <inheritdoc/> /// <inheritdoc/>
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
if (reader.TokenType != JsonTokenType.StartArray) {
throw new Exception($"传入的数据类型错误!应该为数组,现在为{reader.TokenType.ToString()}");
}
var list = new List<string>();
while (reader.Read()) {
if (reader.TokenType == JsonTokenType.StartArray) {
continue;
}
if (reader.TokenType == JsonTokenType.EndArray) {
break;
}
var str = reader.GetString().ToDefault("")!; var str = reader.GetString().ToDefault("")!;
var array = JsonSerializer.Deserialize<string[]>(str) ?? new string[] { }; list.Add(str);
return string.Join(',', array); }
return string.Join(',', list.ToArray());
} }
/// <inheritdoc/> /// <inheritdoc/>
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) { public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) {
var array = this.SplitChars == null ? value.SplitStr() : value.SplitStr(this.SplitChars); var array = this.SplitChars == null ? value.SplitStr() : value.SplitStr(this.SplitChars);
var arrStr = JsonSerializer.Serialize(array); writer.WriteStartArray();
writer.WriteStringValue(arrStr); for (int i = 0; i < array.Length; i++) {
writer.WriteStringValue(array[i]);
}
writer.WriteEndArray();
} }
} }

View File

@ -1,4 +1,5 @@
using System; using System;
using System.Diagnostics.CodeAnalysis;
namespace Falcon.SugarApi namespace Falcon.SugarApi
{ {
@ -20,6 +21,14 @@ namespace Falcon.SugarApi
/// <returns>与IsNullOrEmpty相反</returns> /// <returns>与IsNullOrEmpty相反</returns>
public static bool IsNotNullOrEmpty(this string? str) => !str.IsNullOrEmpty(); public static bool IsNotNullOrEmpty(this string? str) => !str.IsNullOrEmpty();
/// <summary>
/// 当字符串IsNullOrEmpty为True的时候返回默认值否则返回本身
/// </summary>
/// <param name="str">字符串</param>
/// <param name="defaultVal">默认值</param>
/// <returns>字符串本身或默认值</returns>
public static string? ToDefault(this string? str, [NotNull] string defaultVal) => str.IsNullOrEmpty() ? defaultVal : str;
/// <summary> /// <summary>
/// 使用全角半角的逗号句号和分号分割字符串。 /// 使用全角半角的逗号句号和分号分割字符串。
/// </summary> /// </summary>