search
HomeBackend DevelopmentC#.Net TutorialC# implements json serialization and deserialization example code

When doing http communication between asp.net and unity, when the unity client issues a form request, I need to return the data he wants to request to the client in json format for the client to parse. The server side involves the serialization and deserialization of json.

There are examples of both methods. The first is to use a generic collection to store objects, and then serialize the collection; the second is to directly serialize an object

using System;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Runtime.Serialization.Json;
using System.Runtime.Serialization;
using System.IO;
using System.Text;

namespace WebApplication1
{
    //方法一:引入System.Web.Script.Serialization命名空间使用 JavaScriptSerializer类实现简单的序列化
    [Serializable]
    public class Person
    {

        private int id;
        /// <summary>
        /// id
        /// </summary>
        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        private string name;
        /// <summary>
        /// 姓名
        /// </summary>
        public string Name
        {
            get { return name; }
            set { name = value; }
        }
    }
    //方法二:引入 System.Runtime.Serialization.Json命名空间使用 DataContractJsonSerializer类实现序列化
    //可以使用IgnoreDataMember:指定该成员不是数据协定的一部分且没有进行序列化,DataMember:定义序列化属性参数,使用DataMember属性标记字段必须使用DataContract标记类 否则DataMember标记不起作用。
    [DataContract]
    public class Person1
    {

        [IgnoreDataMember]
        public int Id { get; set; }
        [DataMember(Name = "name")]
        public string Name { get; set; }
        [DataMember(Name = "sex")]
        public string Sex { get; set; }
    }
    public partial class _Default : System.Web.UI.Page
    {
        string constr = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString;

        protected void Page_Load(object sender, EventArgs e)
        {

            Person p1 = new Person();
            p1.Id = 1;
            p1.Name = "dxw";
            Person p2 = new Person();
            p2.Id = 2;
            p2.Name = "wn";
            List<Person> listperson = new List<Person>();
            listperson.Add(p1);
            listperson.Add(p2);
            JavaScriptSerializer js = new JavaScriptSerializer();
            //json序列化
            string s = js.Serialize(listperson);
            Response.Write(s);
 
            //方法二
            Person1 p11 = new Person1();
            p11.Id = 1;
            p11.Name = "hello";
            p11.Sex = "男";
            DataContractJsonSerializer json = new DataContractJsonSerializer(p11.GetType());
            string szJson = "";
            //序列化
            using (MemoryStream stream = new MemoryStream())
            {
                json.WriteObject(stream, p11);
                szJson = Encoding.UTF8.GetString(stream.ToArray());
                Response.Write(szJson);
            }
            //反序列化
            //using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
            //{
            //    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(People));
            //    Person1 _people = (Person1)serializer.ReadObject(ms);
            //}
         }
       

        protected void Button1_Click(object sender, EventArgs e)
        {
            Response.Write(constr);
        }

    }

For more articles related to C# implementation of json serialization and deserialization example code, please pay attention to 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
What are the alternatives to NULL in C languageWhat are the alternatives to NULL in C languageMar 03, 2025 pm 05:37 PM

This article explores the challenges of NULL pointer dereferences in C. It argues that the problem isn't NULL itself, but its misuse. The article details best practices for preventing dereferences, including pre-dereference checks, pointer initiali

How to add next-level C compilerHow to add next-level C compilerMar 03, 2025 pm 05:44 PM

This article explains how to create newline characters in C using the \n escape sequence within printf and puts functions. It details the functionality and provides code examples demonstrating its use for line breaks in output.

Which C language compiler is better?Which C language compiler is better?Mar 03, 2025 pm 05:39 PM

This article guides beginners on choosing a C compiler. It argues that GCC, due to its ease of use, wide availability, and extensive resources, is best for beginners. However, it also compares GCC, Clang, MSVC, and TCC, highlighting their differenc

Is NULL still important in modern programming in C language?Is NULL still important in modern programming in C language?Mar 03, 2025 pm 05:35 PM

This article emphasizes the continued importance of NULL in modern C programming. Despite advancements, NULL remains crucial for explicit pointer management, preventing segmentation faults by marking the absence of a valid memory address. Best prac

What are the web versions of C language compilers?What are the web versions of C language compilers?Mar 03, 2025 pm 05:42 PM

This article reviews online C compilers for beginners, focusing on ease of use and debugging capabilities. OnlineGDB and Repl.it are highlighted for their user-friendly interfaces and helpful debugging tools. Other options like Programiz and Compil

C language online programming website C language compiler official website summaryC language online programming website C language compiler official website summaryMar 03, 2025 pm 05:41 PM

This article compares online C programming platforms, highlighting differences in features like debugging tools, IDE functionality, standard compliance, and memory/execution limits. It argues that the "best" platform depends on user needs,

Method of copying code by C language compilerMethod of copying code by C language compilerMar 03, 2025 pm 05:43 PM

This article discusses efficient code copying in C IDEs. It emphasizes that copying is an IDE function, not a compiler feature, and details strategies for improved efficiency, including using IDE selection tools, code folding, search/replace, templa

How to solve the problem of not popping up the output window by the C language compilerHow to solve the problem of not popping up the output window by the C language compilerMar 03, 2025 pm 05:40 PM

This article troubleshoots missing output windows in C program compilation. It examines causes like failing to run the executable, program errors, incorrect compiler settings, background processes, and rapid program termination. Solutions involve ch

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools