C#将字符串格式化为Json

private 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;
           }         
       }

C#将字符串格式化为Json

上一篇:Win10自动更新关闭方法


下一篇:C#语法糖