SoFunction
Updated on 2025-03-08

Example of C# implementing the function of converting JSON and objects between each other

This article describes the implementation of the mutual conversion function between JSON and objects in C#. Share it for your reference, as follows:

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

Address represents the delivery address, DailyRecord represents daily records

using System;
using ;
using ;
using ;
using ;
namespace 
{
  [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; }
  }
}

Help Class Core Code

/// &lt;summary&gt;
/// Convert Json to object/// &lt;/summary&gt;
/// &lt;typeparam name="T"&gt;&lt;/typeparam&gt;
/// &lt;param name="jsonText"&gt;&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
public static T JsonToObject&lt;T&gt;(string jsonText)
{
  DataContractJsonSerializer s = new DataContractJsonSerializer(typeof(T));
  MemoryStream ms = new MemoryStream(Encoding.(jsonText));
  T obj = (T)(ms);
  ();
  return obj;
}
/// &lt;summary&gt;
/// Convert object to JSON/// &lt;/summary&gt;
/// &lt;typeparam name="T"&gt;&lt;/typeparam&gt;
/// &lt;param name="obj"&gt;&lt;/param&gt;
/// &lt;returns&gt;&lt;/returns&gt;
public static string ObjectToJSON&lt;T&gt;(T obj)
{
  DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
  string result = ;
  using (MemoryStream ms = new MemoryStream())
  {
    (ms, obj);
     = 0;
    using (StreamReader read = new StreamReader(ms))
    {
      result = ();
    }
  }
  return result;
}

3. Call

//1.Object-->JSONUserInfo info = new UserInfo
{
    Age = 10,
    Gender = 1,
    UserName = "Andy Lau",
    Lover = new List&lt;string&gt; { "Beauty 1", "Beauty 2", "Beauty 3" },
    Address = new ContactAddress
    {
      Province = "Hunan Province",
      City = "Changsha City",
      Country = "Wangcheng County",
      Details = "A place that can't be found in a certain express delivery"
    },
    DailyRecord = new Dictionary&lt;string, string&gt; { { "Monday", "Have a meal" }, { "Tuesday", "do the laundry" }, { "Wednesday", "Good thing" } }
};
string json = ObjectToJSON&lt;UserInfo&gt;(info);

4. Deserialization results

Copy the codeThe code is as follows:
{"UserName":"Andy Lau","Age":10,"Gender":1,"Lover":["Beauty 1","Beauty 2","Beauty 3"],"Address":{"Province":"Hunan Province","City":"Changsha City","Country":"Wangcheng County","Details":"The place that a certain express delivery cannot be found"},"DailyRecord":[{"Key":"Monday","Value":"Eat"},{"Key":"Tuesday","Value":"Drawing"},{"Key":"Wednesday","Value":"Good things"}]}

PS: Regarding json operation, here are some more practical json online tools for your reference:

OnlineJSONCode verification, inspection, beautification and formatting tools:
http://tools./code/json

JSONOnline formatting tools:
http://tools./code/jsonformat

Online XML/JSONConvert each other tools:
http://tools./code/xmljson

jsonCode online formatting/beautification/compression/editing/converting tools:
http://tools./code/jsoncodeformat

OnlinejsonCompression/escaping tools:
http://tools./code/json_yasuo_trans

For more information about C#, you can also view the special topic of this site: "Summary of C# string operation skills》、《Tutorial on the usage of common C# controls》、《Summary of WinForm control usage》、《Summary of thread usage techniques for C# programming》、《Summary of XML file operation skills in C#》、《C# data structure and algorithm tutorial》、《Summary of C# array operation skills"and"Introduction to C# object-oriented programming tutorial

I hope this article will be helpful to everyone's C# programming.