zoukankan      html  css  js  c++  java
  • [转]C# 将类的内容写成JSON格式的字符串

    将类的内容写入到JSON格式的字符串中

    本例中建立了Person类,赋值后将类中内容写入到字符串中

    运行本代码需要添加引用动态库Newtonsoft.Json

    程序代码:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    //需要引用 Newtonsoft.Json.dll
    using Newtonsoft.Json;
    
    namespace JsonTest
    {
        class Program
        {
            /// <summary>
            /// 人员类
            /// </summary>
            public class Person
            {
                public string name; //姓名
                public int age; //年龄
                public bool sex_is_male; //性别
    
                public struct Partner //伙伴
                {
                    public string partner_name; //伙伴姓名
                    public int partner_age; //伙伴年龄
                    public bool partner_sex_is_male; //伙伴性别
                }
                public Partner partner;
    
                public string[] achievement; //成就
            }
    
            static void Main(string[] args)
            {
                //设置一个Person类
                Person p = new Person();
                p.name = "Tsybius";
                p.age = 23;
                p.sex_is_male = true;
                p.partner.partner_name = "Galatea";
                p.partner.partner_age = 21;
                p.partner.partner_sex_is_male = false;
                p.achievement = new string[] { "ach1", "ach2", "ach3" };
    
                //直接输出
                Console.WriteLine("Formatting.None:");
                string json1 = JsonConvert.SerializeObject(p);
                Console.WriteLine(json1 + "
    ");
    
                //缩进输出
                Console.WriteLine("Formatting.Indented:");
                string json2 = JsonConvert.SerializeObject(p, Formatting.Indented);
                Console.WriteLine(json2 + "
    ");
    
                Console.ReadLine();
            }
        }
    }

    运行结果:

    END

  • 相关阅读:
    10.cocos2dx C++为Sprite添加触摸事件监听器
    9.多彩的幕布layer
    8.ZOrder
    7.cocos精灵创建和绘制
    6.cocos2d设置定时器
    5.cocos2d锚点
    4.cocos场景和层的调用
    文件导入导出
    两个整数相乘是否超限
    倒置字符串函数reverse
  • 原文地址:https://www.cnblogs.com/Raywang80s/p/6891292.html
Copyright © 2011-2022 走看看