Skip to content

Commit 142c98b

Browse files
author
Vicente.Yu
committed
Dto扩展类优化
1 parent bb2f928 commit 142c98b

File tree

2 files changed

+112
-56
lines changed

2 files changed

+112
-56
lines changed

README.md

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -299,9 +299,26 @@ var response = await tenantApi.PostBitableV1AppsByAppTokenTablesByTableIdRecords
299299
ViewId = "vewxxxxxxxxxxxx1u",
300300
});
301301
//对查询结果进行转换
302-
var serialize = response.Data?.Items?.Select(i => i.SerializeFieldsToStringValue(fields.Data?.Items, new BitableRecordSerializer("")));
302+
var serialize = response.Data?.Items?.Select(i => i.SerializeFieldsToStringValue(fields.Data?.Items, new BitableRecordSerializer()));
303303

304304
```
305+
306+
**自定义序列化规则**
307+
```csharp
308+
public class CustomBitableRecordSerializer(string s = "^") : BitableRecordSerializer(s)
309+
{
310+
public override string AttachmentRecordToString(AttachmentRecord[]? record)
311+
{
312+
return JoinCollection(record?.Select(x => $"{x.Name}-{x.FileToken}"));
313+
}
314+
315+
public override string TextRecordToString(TextRecord[]? record)
316+
{
317+
return JoinCollection(record?.Select(x => x.Type switch { "mention" => $"提及{x.Text}", "url" => $"链接{x.Link}", _ => x.Text }));
318+
}
319+
}
320+
```
321+
305322
**说明:**
306323

307324
1. 可以指定`BitableRecordSerializer`参数为数组值分隔符,默认`;`

src/Extensions/DtoExtensions.cs

Lines changed: 94 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
// </copyright>
1212
// <summary></summary>
1313
// ************************************************************************
14+
using System.Text.Json;
15+
1416
#pragma warning disable IDE0130 // 命名空间与文件夹结构不匹配
1517
namespace FeishuNetSdk
1618
#pragma warning restore IDE0130 // 命名空间与文件夹结构不匹配
@@ -20,7 +22,7 @@ namespace FeishuNetSdk
2022
/// </summary>
2123
public static class DtoExtensions
2224
{
23-
static readonly System.Text.Json.JsonSerializerOptions options = new()
25+
static readonly JsonSerializerOptions options = new()
2426
{
2527
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
2628
};
@@ -54,7 +56,7 @@ public static class DtoExtensions
5456
public static Approval.PostApprovalV4InstancesBodyDto SetFormControls(this Approval.PostApprovalV4InstancesBodyDto Dto,
5557
object[] FormControls)
5658
{
57-
Dto.Form = System.Text.Json.JsonSerializer.Serialize(FormControls);
59+
Dto.Form = JsonSerializer.Serialize(FormControls);
5860

5961
return Dto;
6062
}
@@ -66,7 +68,7 @@ public static Approval.PostApprovalV4InstancesBodyDto SetFormControls(this Appro
6668
/// <returns>序列化的控件数组</returns>
6769
public static Approval.Dtos.FormControlDto[]? GetFormControls(this Approval.GetApprovalV4ApprovalsByApprovalCodeResponseDto? Dto)
6870
=> Dto is null ? null
69-
: System.Text.Json.JsonSerializer.Deserialize<Approval.Dtos.FormControlDto[]>(Dto.Form);
71+
: JsonSerializer.Deserialize<Approval.Dtos.FormControlDto[]>(Dto.Form);
7072

7173
/// <summary>
7274
/// 设置消息卡片内容
@@ -99,7 +101,7 @@ public static Im.Spec.PostInteractiveV1CardUpdateBodyDto SetCardObject(this Im.S
99101
public static Im.PatchImV1MessagesByMessageIdBodyDto SetCardObject(this Im.PatchImV1MessagesByMessageIdBodyDto Dto,
100102
Im.Dtos.MessageCard CardObject)
101103
{
102-
Dto.Content = System.Text.Json.JsonSerializer.Serialize(CardObject, CardObject.GetType(), options);
104+
Dto.Content = JsonSerializer.Serialize(CardObject, CardObject.GetType(), options);
103105

104106
return Dto;
105107
}
@@ -147,8 +149,8 @@ private static string SerializeSingleReceiverContent(Im.Dtos.IHasMessageType Car
147149
{
148150
return CardOrContent switch
149151
{
150-
Im.Dtos.PostContent post => System.Text.Json.JsonSerializer.Serialize(post.Post, options),
151-
_ => System.Text.Json.JsonSerializer.Serialize(CardOrContent, CardOrContent.GetType(), options)
152+
Im.Dtos.PostContent post => JsonSerializer.Serialize(post.Post, options),
153+
_ => JsonSerializer.Serialize(CardOrContent, CardOrContent.GetType(), options)
152154
};
153155
}
154156

@@ -421,9 +423,7 @@ public static Im.Dtos.TableElement AddColumn(this Im.Dtos.TableElement Dto, Im.D
421423
/// <returns></returns>
422424
public static Im.Dtos.TableElement SetRows(this Im.Dtos.TableElement Dto, IEnumerable<object> Rows)
423425
{
424-
var data = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, object>[]>(
425-
System.Text.Json.JsonSerializer.Serialize(Rows))
426-
?? Array.Empty<Dictionary<string, object>>();
426+
var data = JsonSerializer.Deserialize<Dictionary<string, object>[]>(JsonSerializer.Serialize(Rows)) ?? [];
427427

428428
if (Dto.Columns.Length > 0)
429429
{
@@ -484,50 +484,27 @@ public static CallbackEvents.CardActionTriggerResponseDto SetCard(this CallbackE
484484
// 该方法用于获取字段的字符串值
485485
private static string? GetFieldValueAsString(object? value, Base.GetBitableV1AppsByAppTokenTablesByTableIdFieldsResponseDto.AppTableFieldForList? field, IBitableRecordSerializer serializer)
486486
{
487-
// 如果值或字段信息为空,则返回 null
488-
if (value is null) return null;
489-
490-
// 调用 ConvertFieldValueToStringByType 方法根据字段类型转换值为字符串
491-
return ConvertFieldValueToStringByType(field?.Type, field?.UiType, value, serializer);
487+
return value is null
488+
? null
489+
: ConvertFieldValueToStringByType(field?.Type, field?.UiType, value, serializer);
492490
}
493491

494492
// 该方法根据字段类型将字段值转换为字符串
495493
private static string? ConvertFieldValueToStringByType(int? type, string? uiType, object value, IBitableRecordSerializer serializer)
496494
{
497495
try
498496
{
499-
// 将值序列化为 JSON 字符串
500-
string json = System.Text.Json.JsonSerializer.Serialize(value);
501-
var jd = System.Text.Json.JsonDocument.Parse(json);
502-
//Console.WriteLine($"type: {type}, ui_type: {uiType}, json: {json}");
503-
504-
string key = GetKey(uiType, type, jd);
505-
object? record = null;
497+
string json = JsonSerializer.Serialize(value);
498+
using var jd = JsonDocument.Parse(json);
499+
string key = GetKey(uiType, type, jd.RootElement);
506500

507-
//Console.WriteLine($"key: {key}");
508501
if (!serializer.TypePairs.TryGetValue(key, out var _type)) return null;
509-
json = AdjustJsonIfArray(_type, jd, json);
510-
//Console.WriteLine($"json: {json}");
511-
record = System.Text.Json.JsonSerializer.Deserialize(json, _type);
502+
json = AdjustJsonIfArray(_type, jd.RootElement, json);
512503

504+
var record = JsonSerializer.Deserialize(json, _type);
513505
if (record is null) return null;
514506

515-
string? result = null;
516-
if (uiType is not null)
517-
{
518-
result = HandleUiType(uiType, record, serializer);
519-
}
520-
else if (type is not null)
521-
{
522-
result = HandleType(type.Value, record, serializer);
523-
}
524-
else
525-
{
526-
result = HandleJsonValueKind(jd.RootElement.ValueKind, record, serializer);
527-
}
528-
529-
//Console.WriteLine(result);
530-
return result;
507+
return GetSerializedValue(uiType, type, jd.RootElement.ValueKind, record, serializer);
531508
}
532509
catch (Exception ex)
533510
{
@@ -537,22 +514,84 @@ record = System.Text.Json.JsonSerializer.Deserialize(json, _type);
537514
}
538515
}
539516

540-
private static string GetKey(string? uiType, int? type, System.Text.Json.JsonDocument jd)
517+
private static string? GetSerializedValue(string? uiType, int? type, JsonValueKind valueKind, object record, IBitableRecordSerializer serializer)
518+
{
519+
if (uiType is not null)
520+
{
521+
return HandleUiType(uiType, record, serializer);
522+
}
523+
else if (type is not null)
524+
{
525+
return HandleType(type.Value, record, serializer);
526+
}
527+
else
528+
{
529+
return HandleJsonValueKind(valueKind, record, serializer);
530+
}
531+
}
532+
533+
private static string GetKey(string? uiType, int? type, JsonElement je)
541534
{
542535
return uiType is not null
543536
? uiType
544537
: type is not null
545538
? $"Type{type}"
546-
: $"JsonValueKind{jd.RootElement.ValueKind}";
539+
: $"JsonValueKind{je.ValueKind}";
540+
}
541+
542+
private static string AdjustJsonIfArray(Type _type, JsonElement je, string json)
543+
{
544+
return _type.IsArray && je.ValueKind != JsonValueKind.Array
545+
? ConvertToJsonArray(je).GetRawText()
546+
: json;
547+
}
548+
549+
private static JsonElement ConvertToJsonArray(JsonElement element)
550+
{
551+
using var memoryStream = new MemoryStream();
552+
using var jsonWriter = new Utf8JsonWriter(memoryStream);
553+
554+
jsonWriter.WriteStartArray();
555+
WriteJsonElementToWriter(jsonWriter, element);
556+
jsonWriter.WriteEndArray();
557+
jsonWriter.Flush();
558+
559+
var jsonBytes = memoryStream.ToArray();
560+
return JsonDocument.Parse(jsonBytes).RootElement;
547561
}
548562

549-
private static string AdjustJsonIfArray(Type _type, System.Text.Json.JsonDocument jd, string json)
563+
private static void WriteJsonElementToWriter(Utf8JsonWriter writer, JsonElement element)
550564
{
551-
if (_type.IsArray && jd.RootElement.ValueKind != System.Text.Json.JsonValueKind.Array)
565+
try
566+
{
567+
switch (element.ValueKind)
568+
{
569+
case JsonValueKind.Object:
570+
writer.WriteRawValue(element.GetRawText());
571+
break;
572+
case JsonValueKind.String:
573+
writer.WriteStringValue(element.GetString());
574+
break;
575+
case JsonValueKind.Number:
576+
writer.WriteNumberValue(element.GetDouble());
577+
break;
578+
case JsonValueKind.True:
579+
case JsonValueKind.False:
580+
writer.WriteBooleanValue(element.GetBoolean());
581+
break;
582+
case JsonValueKind.Null:
583+
writer.WriteNullValue();
584+
break;
585+
default:
586+
// 其他情况,可根据需求扩展处理逻辑
587+
break;
588+
}
589+
}
590+
catch (Exception ex)
552591
{
553-
json = $"[{json}]";
592+
// 可以根据实际情况记录日志或进行其他处理
593+
Console.WriteLine($"Error writing JSON element: {ex.Message}");
554594
}
555-
return json;
556595
}
557596

558597
private static string? HandleUiType(string uiType, object record, IBitableRecordSerializer serializer)
@@ -618,19 +657,19 @@ 19 or 20 when record is Base.Dtos.FormulaRecord f
618657
};
619658
}
620659

621-
private static string? HandleJsonValueKind(System.Text.Json.JsonValueKind valueKind, object record, IBitableRecordSerializer serializer)
660+
private static string? HandleJsonValueKind(JsonValueKind valueKind, object record, IBitableRecordSerializer serializer)
622661
{
623662
return valueKind switch
624663
{
625-
System.Text.Json.JsonValueKind.False
626-
or System.Text.Json.JsonValueKind.True => serializer.CheckboxRecordToString(record as bool[]),
627-
System.Text.Json.JsonValueKind.Number => serializer.NumberRecordToString(record as decimal[]),
628-
System.Text.Json.JsonValueKind.String => serializer.TextRecordToString(record as Base.Dtos.TextRecord[]),
629-
System.Text.Json.JsonValueKind.Object when record is Base.Dtos.FormulaRecord f
664+
JsonValueKind.False
665+
or JsonValueKind.True => serializer.CheckboxRecordToString(record as bool[]),
666+
JsonValueKind.Number => serializer.NumberRecordToString(record as decimal[]),
667+
JsonValueKind.String => serializer.TextRecordToString(record as Base.Dtos.TextRecord[]),
668+
JsonValueKind.Object when record is Base.Dtos.FormulaRecord f
630669
=> ConvertFieldValueToStringByType(f.Type, null, f.Value, serializer),
631-
System.Text.Json.JsonValueKind.Array => serializer.TextRecordToString(record as Base.Dtos.TextRecord[]),
670+
JsonValueKind.Array => serializer.TextRecordToString(record as Base.Dtos.TextRecord[]),
632671
_ => null
633672
};
634673
}
635674
}
636-
}
675+
}

0 commit comments

Comments
 (0)