1. 程式人生 > >JSON序列化與反序列化匿名型別

JSON序列化與反序列化匿名型別

一、序列化匿名型別

1.序列化一個var型別

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;

namespace JSONDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var definition = new { Name = "GongHui", Age = 28, Major = ".NET工程師" };

            string json = JsonConvert.SerializeObject(definition);
            Console.WriteLine(json);
        }
    }
}


2.序列化執行結果

二、反序列化匿名型別

1.JSON反序列化var

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using GongHuiNewtonsoft.Json;

namespace JSONDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            var definition = new { Name = "", Age = 0, Major = "" };

            string json1 = @"{'Name':'GongHui','Age':28,'Major':'.NET ENGINEER'}";
            var person1 = JsonConvert.DeserializeAnonymousType(json1, definition);
            Console.WriteLine("---------person1-------------");
            Console.WriteLine(person1.Name);
            Console.WriteLine(person1.Age);
            Console.WriteLine(person1.Major);

            string json2 = @"{'Name':'Jack','Major':'DRIVER'}";
            var person2 = JsonConvert.DeserializeAnonymousType(json2, definition);
            Console.WriteLine("---------person2-------------");
            Console.WriteLine(person2.Name);
            Console.WriteLine(person2.Age);
            Console.WriteLine(person2.Major);
        }
    }
}


2.反序列執行結果