Example Analysis of C Programming to Realize Mutual Conversion between Object and JSON String

  • 2021-08-28 20:53:11
  • OfStack

In this paper, an example is given to analyze the method of converting C # object to JSON string. Share it for your reference, as follows:

DoNet 2.0 requires Newtonsoft. Json. dll

The code is as follows:


using System;
using System.IO;
using System.Text;
using Newtonsoft.Json;
namespace OfflineAcceptControl.UCTools
{
  public class JsonTools
  {
    //  From 1 Individual object information generation Json String 
    public static string ObjectToJson(object obj)
    {
      return JavaScriptConvert.SerializeObject(obj);
    }
    //  From 1 A Json String generation object information 
    public static object JsonToObject(string jsonString, object obj)
    {
      return JavaScriptConvert.DeserializeObject(jsonString, obj.GetType());
    }
  }
}

Donet 3.5 comes with DLL processing json string

Note references: System. Runtime. Serialization, System. ServiceModel. Web

The code is as follows:


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
namespace CrjIIOfflineAccept.CrjIITools
{
  public class JsonTools
  {
    //  From 1 Individual object information generation Json String 
    public static string ObjectToJson(object obj)
    {
      DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
      MemoryStream stream = new MemoryStream();
      serializer.WriteObject(stream, obj);
      byte[] dataBytes = new byte[stream.Length];
      stream.Position = 0;
      stream.Read(dataBytes, 0, (int)stream.Length);
      return Encoding.UTF8.GetString(dataBytes);
    }
    //  From 1 A Json String generation object information 
    public static object JsonToObject(string jsonString, object obj)
    {
      DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
      MemoryStream mStream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
      return serializer.ReadObject(mStream);
    }
  }
}

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


Related articles: