• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
PowerCoder
博客园    首页    新随笔    联系   管理    订阅  订阅

C#支持将json中的多种类型反序列化为object类型

我们知道json中的字段是弱类型的,也就是说json中的一个字段不用事先声明具体的类型,这就导致json中某个字段的值有可能是字符串,也有可能是数字,也有可能是布尔值,其它等。。。但是C#是强类型的,定义一个C#类中字段的时候,必须声明它是什么类型,所以我们可以将json中有不同类型的字段在C#中定义为object类型,来看如下代码示例:

using Newtonsoft.Json;

namespace Net8JsonDemo
{
    class JsonDto
    {
        public string? Name
        {
            get;
            set;
        }

        public int? Age
        {
            get;
            set;
        }

        public object? Value
        {
            get;
            set;
        }

        public object[]? Values
        {
            get;
            set;
        }
    }


    internal class Program
    {
        static void Main(string[] args)
        {
            string jsonWithStringValue = "{\"Name\":\"王大锤,James Wang\",\"Value\":\"你好,Hello\",\"Values\":[\"测试,testing\",1000,true]}";
            string jsonWithNumberValue = "{\"Name\":\"王大锤,James Wang\",\"Value\":2000,\"Values\":[\"测试,testing\",1000,true]}";
            string jsonWithBooleanValue = "{\"Name\":\"王大锤,James Wang\",\"Value\":false,\"Values\":[\"测试,testing\",1000,true]}";
            string jsonWithNullValue = "{\"Name\":\"王大锤,James Wang\",\"Value\":null,\"Values\":[\"测试,testing\",1000,true]}";

            JsonDto? jsonWithStringValueDto = JsonConvert.DeserializeObject<JsonDto>(jsonWithStringValue);
            JsonDto? jsonWithNumberValueDto = JsonConvert.DeserializeObject<JsonDto>(jsonWithNumberValue);
            JsonDto? jsonWithBooleanValueDto = JsonConvert.DeserializeObject<JsonDto>(jsonWithBooleanValue);
            JsonDto? jsonWithNullValueDto = JsonConvert.DeserializeObject<JsonDto>(jsonWithNullValue);

            Type? jsonWithStringValueDtoType = jsonWithStringValueDto?.Value?.GetType();
            Type? jsonWithNumberValueDtoType = jsonWithNumberValueDto?.Value?.GetType();
            Type? jsonWithBooleanValueDtoType = jsonWithBooleanValueDto?.Value?.GetType();
            Type? jsonWithNullValueDtoType = jsonWithNullValueDto?.Value?.GetType();

            Console.WriteLine($"jsonWithStringValueDtoType is {jsonWithStringValueDtoType?.ToString()}"); //输出:jsonWithStringValueDtoType is System.String
            Console.WriteLine($"jsonWithNumberValueDtoType is {jsonWithNumberValueDtoType?.ToString()}"); //输出:jsonWithNumberValueDtoType is System.Int64
            Console.WriteLine($"jsonWithBooleanValueDtoType is {jsonWithBooleanValueDtoType?.ToString()}"); //输出:jsonWithBooleanValueDtoType is System.Boolean
            Console.WriteLine($"jsonWithNullValueDtoType is {jsonWithNullValueDtoType?.ToString()}"); //输出:jsonWithNullValueDtoType is
            Console.WriteLine($"jsonWithStringValueDto.Values[0] is {jsonWithStringValueDto?.Values?[0]?.GetType()?.ToString()}"); //输出:jsonWithStringValueDto.Values[0] is System.String
            Console.WriteLine($"jsonWithStringValueDto.Values[1] is {jsonWithStringValueDto?.Values?[1]?.GetType()?.ToString()}"); //输出:jsonWithStringValueDto.Values[1] is System.Int64
            Console.WriteLine($"jsonWithStringValueDto.Values[2] is {jsonWithStringValueDto?.Values?[2]?.GetType()?.ToString()}"); //输出:jsonWithStringValueDto.Values[2] is System.Boolean

            jsonWithStringValue = JsonConvert.SerializeObject(jsonWithStringValueDto);
            Console.WriteLine($"jsonWithStringValueDto after serialization is \n{jsonWithStringValue}");
            /*输出:
              jsonWithStringValueDto after serialization is
              {"Name":"王大锤,James Wang","Age":null,"Value":"你好,Hello","Values":["测试,testing",1000,true]}
            */

            jsonWithNullValue = JsonConvert.SerializeObject(jsonWithNullValueDto);
            Console.WriteLine($"jsonWithNullValueDto after serialization is \n{jsonWithNullValue}");
            /*输出:
              jsonWithNullValueDto after serialization is
              {"Name":"王大锤,James Wang","Age":null,"Value":null,"Values":["测试,testing",1000,true]}
            */

            Console.WriteLine("-----------------------------------------------------------------");

            Dictionary<string, object> row1 = new Dictionary<string, object>();
            row1.Add("Name", "张飞,zhangfei");
            row1.Add("Age", 21);
            row1.Add("Flag", true);

            Dictionary<string, object> row2 = new Dictionary<string, object>();
            row2.Add("Name", "关羽,guanyu");
            row2.Add("Flag", false);

            Dictionary<string, object> row3 = new Dictionary<string, object>();
            row3.Add("Name", "刘备,liubei");
            row3.Add("Age", 21);
            row3.Add("Flag", true);

            List<Dictionary<string, object>>? jsonCollection = new List<Dictionary<string, object>>();
            jsonCollection.Add(row1);
            jsonCollection.Add(row2);
            jsonCollection.Add(row3);

            string json = JsonConvert.SerializeObject(jsonCollection);

            Console.WriteLine($"The jsonCollection after serialization is \n{json}");
            /*输出:
             The jsonCollection after serialization is
             [{"Name":"张飞,zhangfei","Age":21,"Flag":true},{"Name":"关羽,guanyu","Flag":false},{"Name":"刘备,liubei","Age":21,"Flag":true}]
            */

            jsonCollection = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json);

            Console.WriteLine($"Type of jsonCollection[0].Name is {jsonCollection?[0]?["Name"]?.GetType()?.ToString()}"); //输出:Type of jsonCollection[0].Name is System.String
            Console.WriteLine($"Type of jsonCollection[0].Age is {jsonCollection?[0]?["Age"]?.GetType()?.ToString()}"); //输出:Type of jsonCollection[0].Age is System.Int64
            Console.WriteLine($"Type of jsonCollection[0].Flag is {jsonCollection?[0]?["Flag"]?.GetType()?.ToString()}"); //输出:Type of jsonCollection[0].Flag is System.Boolean

            Console.WriteLine($"Value of jsonCollection[0].Name is {jsonCollection?[0]?["Name"]?.ToString()}"); //输出:Value of jsonCollection[0].Name is 张飞,zhangfei
            Console.WriteLine($"Value of jsonCollection[1].Name is {jsonCollection?[1]?["Name"]?.ToString()}"); //输出:Value of jsonCollection[1].Name is 关羽,guanyu
            Console.WriteLine($"Value of jsonCollection[2].Name is {jsonCollection?[2]?["Name"]?.ToString()}"); //输出:Value of jsonCollection[2].Name is 刘备,liubei

            Console.WriteLine("Press any key to end...");
            Console.ReadLine();
        }
    }
}

本例中我们使用的是Json.NET来序列化和反序列化json,其它框架应该类似,我们可以看到C#的object类型,可以用来装json支持的所有字段类型,完美兼容json的弱类型。

 

posted @ 2024-11-20 16:31  PowerCoder  阅读(386)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3