Home  >  Article  >  Backend Development  >  Example of how C# implements the conversion function between JSON and objects

Example of how C# implements the conversion function between JSON and objects

黄舟
黄舟Original
2017-09-02 14:18:181677browse

This article mainly introduces the function of converting between JSON and objects in C#, and analyzes the operation skills of converting between objects and json in C# in detail in the form of examples. Friends in need can refer to it

The example in this article describes how C# implements the conversion function between JSON and objects. Share it with everyone for your reference, the details are as follows:

1. First, declare the user information object, DataContract modified class, indicating that it can be parsed into JSON, DataMember modified attributes, Order indicates the order of parsing, and Lover is an array List, indicating the number of girlfriends

Address represents the shipping address, DailyRecord represents daily records


##

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 help class core code


/// <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. Call


//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. The result after deserialization

The code is as follows:


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

The above is the detailed content of Example of how C# implements the conversion function between JSON and objects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn