JSON 数据转换

JSON概述


     JSON(Java Script Object Notation)JS对象符号,通常JSON和XML是二选一的,JSON的数据格式很类似于JavaScript的对象。

{
  "pets": {
    "name": "Jeffrey",
    "species": "Giraffe"
  }
}


.NET原生方式进行数据转换


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
 
    public class JsonHelper
    {
        public static string ToJson<T>(T obj)
        {
            string result = String .Empty;
            try
            {
                System.Runtime.Serialization.Json. DataContractJsonSerializer serializer =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer( typeof(T));
                using (System.IO.MemoryStream ms = new System.IO. MemoryStream())
                {
                    serializer.WriteObject(ms, obj);
                    result = System.Text. Encoding.UTF8.GetString(ms.ToArray());
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }
 
        public static string ToJsonFromByList<T>( List<T> vals)
        {
            System.Text. StringBuilder st = new System.Text.StringBuilder();
            try
            {
                System.Runtime.Serialization.Json. DataContractJsonSerializer s = new System.Runtime.Serialization.Json.DataContractJsonSerializer (typeof(T));
 
                foreach (T city in vals)
                {
                    using (System.IO.MemoryStream ms = new System.IO. MemoryStream())
                    {
                        s.WriteObject(ms, city);
                        st.Append(System.Text. Encoding.UTF8.GetString(ms.ToArray()));
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
 
            return st.ToString();
        }
 
        public static T ParseFormByJson<T>(string jsonStr)
        {
            T obj = Activator.CreateInstance<T>();
            using (System.IO.MemoryStream ms =
            new System.IO.MemoryStream (System.Text.Encoding.UTF8.GetBytes(jsonStr)))
            {
                System.Runtime.Serialization.Json. DataContractJsonSerializer serializer =
                new System.Runtime.Serialization.Json.DataContractJsonSerializer( typeof(T));
                return (T)serializer.ReadObject(ms);
            }
        }
    }  

Newtonsoft.json组件方式进行数据转换


     采用Newtonsoft.json组件方式实现json数据的转换需要引用Newtonsoft.json组件。下载地址:http://download.csdn.net/detail/aaakingwin/5726429

  • 简易方式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 
using Newtonsoft.Json;
 
 
    public class JsonHelper
    {
        public static string ToJson<T>(T value)
        {
            return JsonConvert .SerializeObject(value,Formatting.None);
        }
 
        public static T FromJson<T>(string jsonText)
        {
            return JsonConvert .DeserializeObject<T>(jsonText); ;
        }
    }

  • 复杂可配置方式
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text; 
using Newtonsoft.Json;
using System.IO;
 
   public static string ToJson<T>(T value)
        {
            Newtonsoft.Json. JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
            json.NullValueHandling = NullValueHandling.Ignore;
            json.ObjectCreationHandling = Newtonsoft.Json. ObjectCreationHandling.Replace;
            json.MissingMemberHandling = Newtonsoft.Json. MissingMemberHandling.Ignore;
            json.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
            StringWriter sw = new StringWriter();
            Newtonsoft.Json. JsonTextWriter writer = new JsonTextWriter(sw);
            writer.Formatting = Formatting.None;
            writer.QuoteChar = '"';
            json.Serialize(writer, value);
            string output = sw.ToString();
            writer.Close();
            sw.Close();
            return output;
        }
      
        public static T FromJson<T>(string jsonText)
        {
            Newtonsoft.Json. JsonSerializer json = new Newtonsoft.Json.JsonSerializer();
            json.NullValueHandling = Newtonsoft.Json. NullValueHandling.Ignore;
            json.ObjectCreationHandling = Newtonsoft.Json. ObjectCreationHandling.Replace;
            json.MissingMemberHandling = Newtonsoft.Json. MissingMemberHandling.Ignore;
            json.ReferenceLoopHandling = Newtonsoft.Json. ReferenceLoopHandling.Ignore;
            StringReader sr = new StringReader(jsonText);
            Newtonsoft.Json. JsonTextReader reader = new JsonTextReader(sr);
            T result = (T)json.Deserialize(reader, typeof(T));
            reader.Close();
            return result;
        }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值