Using System.Json for non-Silverlight projects?

前端 未结 5 1866
鱼传尺愫
鱼传尺愫 2020-12-31 10:18

Any idea on how to do it? If not possible, what\'s a good JSON library for C#?

5条回答
  •  醉梦人生
    2020-12-31 11:15

    Here's an extenstion method to serialize any object instance to JSON:

    public static class GenericExtensions
    {
        public static string ToJsonString(this T input)
        {
            string json;
            DataContractJsonSerializer ser = new DataContractJsonSerializer(input.GetType());
            using (MemoryStream ms = new MemoryStream())
            {
                ser.WriteObject(ms, input);
                json = Encoding.Default.GetString(ms.ToArray());
            }
            return json;
        }
    }
    

    You'll need to add a reference to System.ServiceModel.Web to use the DataContractSerializer.

提交回复
热议问题