C#怎么实现JSON与对象之间互相转换功能

发布时间:2020-09-22 09:34:27 作者:小新
来源:亿速云 阅读:272

这篇文章主要介绍C#怎么实现JSON与对象之间互相转换功能,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

1.首先是声明用户信息对象,DataContract修饰类,表示可以被解析成JSON,DataMember修饰属性,Order表示 解析的顺序,另外Lover是数组列表,表示女朋友个数

Address 表示送货地址,DailyRecord  表示日常记录

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace FunctionTest.Model
{
  [DataContract]
  public class UserInfo
  {
    [DataMember(Order =0)]
    public string UserName { get; set; }
    [DataMember(Order = 1)]
    public int Age { get; set; }
    [DataMember(Order = 2)]
    public int Gender { get; set; }
    [DataMember(Order =3)]
    public List<string> Lover { get; set; }
    [DataMember(Order = 4)]
    public ContactAddress Address { get; set; }
    [DataMember(Order = 5)]
    public Dictionary<string, string> DailyRecord {
      get; set;
    }
  }
  [DataContract]
  public class ContactAddress
  {
    [DataMember(Order =0)]
    public string Province { get; set; }
    [DataMember(Order = 1)]
    public string City { get; set; }
    [DataMember(Order = 2)]
    public string Country { get; set; }
    [DataMember(Order = 3)]
    public string Details { get; set; }
  }
}

2.JSON帮助类 核心代码

/// <summary>
/// Json转换成对象
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="jsonText"></param>
/// <returns></returns>
public static T JsonToObject<T>(string jsonText)
{
  DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));
  MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
  T obj = (T)s.ReadObject(ms);
  ms.Dispose();
  return obj;
}
/// <summary>
/// 对象转换成JSON
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static string ObjectToJSON<T>(T obj)
{
  DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
  string result = string.Empty;
  using (MemoryStream ms = new MemoryStream())
  {
    serializer.WriteObject(ms, obj);
    ms.Position = 0;
    using (StreamReader read = new StreamReader(ms))
    {
      result = read.ReadToEnd();
    }
  }
  return result;
}

3.调用

//1.对象-->JSON
UserInfo info = new UserInfo
{
    Age = 10,
    Gender = 1,
    UserName = "刘德华",
    Lover = new List<string> { "美女1", "美女2", "美女3" },
    Address = new ContactAddress
    {
      Province = "湖南省",
      City = "长沙市",
      Country = "望城县",
      Details = "某旮旯快递找不到的地方"
    },
    DailyRecord = new Dictionary<string, string> { { "星期一", "吃饭" }, { "星期二", "洗衣服" }, { "星期三", "好事情" } }
};
string json = ObjectToJSON<UserInfo>(info);

4.反序列化后的结果

代码如下:

{"UserName":"刘德华","Age":10,"Gender":1,"Lover":["美女1","美女2","美女3"],"Address":{"Province":"湖南省","City":"长沙市","Country":"望城县",
"Details":"某旮旯快递找不到的地方"},"DailyRecord":[{"Key":"星期一","Value":"吃饭"},{"Key":"星期二","Value":"洗衣服"},{"Key":"星期三","Value":"好事情"}]}

以上是C#怎么实现JSON与对象之间互相转换功能的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. Python中:dict(或对象)与json之间的互相转化
  2. jQuery对象与JS原生dom对象之间的转换

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

javascript csharp

上一篇:python选取特定列 pandas iloc,loc,icol的使用详解(列切片及行切片)

下一篇:php怎么封装方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》