C#将字符串格式化为Json
2021-05-23 15:31
标签:nbsp ToJson ons plain comment string indent alt null C#将字符串格式化为Json 标签:nbsp ToJson ons plain comment string indent alt null 原文地址:https://www.cnblogs.com/LCLBook/p/11137384.htmlprivate
string
ConvertStringToJson(
string
str)
{
//格式化json字符串
JsonSerializer serializer =
new
JsonSerializer();
TextReader tr =
new
StringReader(str);
JsonTextReader jtr =
new
JsonTextReader(tr);
object
obj = serializer.Deserialize(jtr);
if
(obj !=
null
)
{
StringWriter textWriter =
new
StringWriter();
JsonTextWriter jsonWriter =
new
JsonTextWriter(textWriter)
{
Formatting = Formatting.Indented,
Indentation = 4,
IndentChar =
‘ ‘
};
serializer.Serialize(jsonWriter, obj);
return
textWriter.ToString();
}
else
{
return
str;
}
}