C# 如何把含有换行、缩进、转义符的Json字符串转换为没有换行、缩进、转义符的字符串
时间: 2024-09-25 17:14:59 浏览: 256
在C#中,你可以使用`System.Text.Json`库来处理Json字符串,并通过`JsonSerializer.Serialize()`方法序列化带有格式的Json对象到一个简单的字符串,去除换行、缩进和转义字符。下面是一个示例:
```csharp
using System;
using System.Text.Json;
public class YourJsonObject
{
// ...你的对象成员...
}
public static string RemoveFormattingFromJson(JsonObject obj)
{
// 使用JsonSerializerOptions去掉默认格式
var options = new JsonSerializerOptions { Indentation = 0, PropertyNameCaseInsensitive = true };
// 将对象转换为无格式的字符串
return JsonSerializer.Serialize(obj, options);
}
// 示例用法
YourJsonObject yourObj = new YourJsonObject();
string formattedJson = Remove FormattingFromJson(yourObj);
```
在这个例子中,`Indentation = 0`指定不保留缩进,`PropertyNameCaseInsensitive = true`则忽略属性名的大小写。`JsonSerializer.Serialize()`会返回一个没有换行和多余缩进的Json字符串。
阅读全文
相关推荐

















