forked from ServiceStack/ServiceStack.Text
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTextExtensions.cs
More file actions
80 lines (73 loc) · 2.44 KB
/
TextExtensions.cs
File metadata and controls
80 lines (73 loc) · 2.44 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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//
// https://github.com/ServiceStack/ServiceStack.Text
// ServiceStack.Text: .NET C# POCO JSON, JSV and CSV Text Serializers.
//
// Authors:
// Demis Bellot (demis.bellot@gmail.com)
//
// Copyright 2012 ServiceStack Ltd.
//
// Licensed under the same terms of ServiceStack: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Text;
using ServiceStack.Text.Common;
namespace ServiceStack.Text
{
public static class TextExtensions
{
public static string ToCsvField(this string text)
{
return string.IsNullOrEmpty(text) || !CsvWriter.HasAnyEscapeChars(text)
? text
: string.Concat
(
CsvConfig.ItemDelimiterString,
text.Replace(CsvConfig.ItemDelimiterString, CsvConfig.EscapedItemDelimiterString),
CsvConfig.ItemDelimiterString
);
}
public static object ToCsvField(this object text)
{
return text == null || !JsWriter.HasAnyEscapeChars(text.ToString())
? text
: string.Concat
(
JsWriter.QuoteString,
text.ToString().Replace(JsWriter.QuoteString, TypeSerializer.DoubleQuoteString),
JsWriter.QuoteString
);
}
public static string FromCsvField(this string text)
{
return string.IsNullOrEmpty(text) || !text.StartsWith(CsvConfig.ItemDelimiterString)
? text
: text.Substring(CsvConfig.ItemDelimiterString.Length, text.Length - CsvConfig.EscapedItemDelimiterString.Length)
.Replace(CsvConfig.EscapedItemDelimiterString, CsvConfig.ItemDelimiterString);
}
public static List<string> FromCsvFields(this IEnumerable<string> texts)
{
var safeTexts = new List<string>();
foreach (var text in texts)
{
safeTexts.Add(FromCsvField(text));
}
return safeTexts;
}
public static string[] FromCsvFields(params string[] texts)
{
var textsLen = texts.Length;
var safeTexts = new string[textsLen];
for (var i = 0; i < textsLen; i++)
{
safeTexts[i] = FromCsvField(texts[i]);
}
return safeTexts;
}
public static string SerializeToString<T>(this T value)
{
return JsonSerializer.SerializeToString(value);
}
}
}