Home > Backend Development > C#.Net Tutorial > Implementation method of converting between String type and json in C#

Implementation method of converting between String type and json in C#

黄舟
Release: 2017-09-15 11:20:26
Original
4741 people have browsed it

This article mainly introduces the mutual conversion function between String type and json in C#, involving the construction and conversion of C# json format data. Friends in need can refer to the following

Examples of this article Use C# to implement the mutual conversion function between String type and json. Share it with everyone for your reference, the details are as follows:


////Donet2.0 需要添加引用
// 从一个对象信息生成Json串
public static string ObjectToJson(object obj)
{
   return JavaScriptConvert.SerializeObject(obj);
}
// 从一个Json串生成对象信息
public static object JsonToObject(string jsonString,object obj)
{
   return JavaScriptConvert.DeserializeObject(jsonString, obj.GetType());
}
//Donet3.5自带了DLL处理json串
//注意引用:System.Runtime.Serialization,System.ServiceModel.Web
Copy after login

Code


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
  {
    // 从一个对象信息生成Json串
    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);
    }
    // 从一个Json串生成对象信息
    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);
    }
  }
}
Copy after login

The above is the detailed content of Implementation method of converting between String type and json in C#. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template