From df23896b4db5217fa8b68c74fe22d5a586b8977f Mon Sep 17 00:00:00 2001
From: falcon <9504402@qq.com>
Date: Wed, 25 May 2022 09:19:38 +0800
Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8DArrayString=E9=94=99=E8=AF=AF?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.../JsonSerialize/ArrayJsonConverter.cs | 26 +++++++++++++++----
Falcon.SugarApi/StringExtend.cs | 9 +++++++
2 files changed, 30 insertions(+), 5 deletions(-)
diff --git a/Falcon.SugarApi/JsonSerialize/ArrayJsonConverter.cs b/Falcon.SugarApi/JsonSerialize/ArrayJsonConverter.cs
index d3bd10c..6db9385 100644
--- a/Falcon.SugarApi/JsonSerialize/ArrayJsonConverter.cs
+++ b/Falcon.SugarApi/JsonSerialize/ArrayJsonConverter.cs
@@ -1,4 +1,5 @@
using System;
+using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
@@ -16,15 +17,30 @@ namespace Falcon.SugarApi.JsonSerialize
///
public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
- var str = reader.GetString().ToDefault("")!;
- var array = JsonSerializer.Deserialize(str) ?? new string[] { };
- return string.Join(',', array);
+ if (reader.TokenType != JsonTokenType.StartArray) {
+ throw new Exception($"传入的数据类型错误!应该为数组,现在为{reader.TokenType.ToString()}");
+ }
+ var list = new List();
+ while (reader.Read()) {
+ if (reader.TokenType == JsonTokenType.StartArray) {
+ continue;
+ }
+ if (reader.TokenType == JsonTokenType.EndArray) {
+ break;
+ }
+ var str = reader.GetString().ToDefault("")!;
+ list.Add(str);
+ }
+ return string.Join(',', list.ToArray());
}
///
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) {
var array = this.SplitChars == null ? value.SplitStr() : value.SplitStr(this.SplitChars);
- var arrStr = JsonSerializer.Serialize(array);
- writer.WriteStringValue(arrStr);
+ writer.WriteStartArray();
+ for (int i = 0; i < array.Length; i++) {
+ writer.WriteStringValue(array[i]);
+ }
+ writer.WriteEndArray();
}
}
diff --git a/Falcon.SugarApi/StringExtend.cs b/Falcon.SugarApi/StringExtend.cs
index 41ee913..ef3a83f 100644
--- a/Falcon.SugarApi/StringExtend.cs
+++ b/Falcon.SugarApi/StringExtend.cs
@@ -1,4 +1,5 @@
using System;
+using System.Diagnostics.CodeAnalysis;
namespace Falcon.SugarApi
{
@@ -20,6 +21,14 @@ namespace Falcon.SugarApi
/// 与IsNullOrEmpty相反
public static bool IsNotNullOrEmpty(this string? str) => !str.IsNullOrEmpty();
+ ///
+ /// 当字符串IsNullOrEmpty为True的时候返回默认值,否则返回本身
+ ///
+ /// 字符串
+ /// 默认值
+ /// 字符串本身或默认值
+ public static string? ToDefault(this string? str, [NotNull] string defaultVal) => str.IsNullOrEmpty() ? defaultVal : str;
+
///
/// 使用全角半角的逗号句号和分号分割字符串。
///