码迷,mamicode.com
首页 > Web开发 > 详细

C# DataContractJsonSerializer 处理Json

时间:2014-09-25 12:24:18      阅读:290      评论:0      收藏:0      [点我收藏+]

标签:blog   http   io   os   ar   sp   cti   on   c   

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.ServiceModel.Web;
using System.IO;
namespace Json1
{
    class Program
    {
        [DataContract(Namespace = "http://blog.csdn.net/longhaoyou")]
        public class JsonData
        {
            [DataMember(Order = 0)]
            public string id { get; set; }
            [DataMember(Order=1)]
            public string name { get; set; }
        }

        public static string JsonToString<T>(T value)
        {
             var vStream=new MemoryStream();
             DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
             serializer.WriteObject(vStream, value);
             byte[] jsondata = new byte[vStream.Length];
             vStream.Position = 0;
             if (vStream.Read(jsondata, 0, jsondata.Length) != jsondata.Length)
                 throw new Exception("读取出错");
             return Encoding.UTF8.GetString(jsondata);
        }

        public static T StringToJson<T>(string text) 
        {
            byte[] jsondata = Encoding.UTF8.GetBytes(text);
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            var vStream=new MemoryStream(jsondata);
            return (T)serializer.ReadObject(vStream);
        }
        static void Main(string[] args)
        {
            JsonData data = new JsonData() { id = "0001", name = "龙号友" };
            string jsontext = JsonToString(data);
            Console.WriteLine(jsontext);
            data = StringToJson<JsonData>(jsontext);
        }
    }
}

C# DataContractJsonSerializer 处理Json

标签:blog   http   io   os   ar   sp   cti   on   c   

原文地址:http://blog.csdn.net/longhaoyou/article/details/39546331

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!