How to create JSON string in C#

后端 未结 14 1152
闹比i
闹比i 2020-11-22 12:39

I just used the XmlWriter to create some XML to send back in an HTTP response. How would you create a JSON string. I assume you would just use a stringbuilder to build the

14条回答
  •  一生所求
    2020-11-22 13:33

    This code snippet uses the DataContractJsonSerializer from System.Runtime.Serialization.Json in .NET 3.5.

    public static string ToJson(/* this */ T value, Encoding encoding)
    {
        var serializer = new DataContractJsonSerializer(typeof(T));
    
        using (var stream = new MemoryStream())
        {
            using (var writer = JsonReaderWriterFactory.CreateJsonWriter(stream, encoding))
            {
                serializer.WriteObject(writer, value);
            }
    
            return encoding.GetString(stream.ToArray());
        }
    }
    

提交回复
热议问题