首页 > 解决方案 > 将 dotnet core 中的模型类转换为 json

问题描述

我需要将我为其创建模型类的实体框架实体转换为 json。
换句话说,我需要从我的实体生成一个 json 模型。请问这可能吗?
我在互联网上搜索过,我发现的只是序列化对象,但这不能满足我的需要,我不会在 json 上获取对象,我需要将它自己的类转换为 JSON。
在此处输入图像描述

代码:

class : 
    public class Course
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }

        public ICollection<Enrollment> Enrollments { get; set; }
    }

我需要的 :

key : CourseID,
name : Course,
Properties:
{ 
CourseID: Int,
Title: String,
credits: Int
...
}

标签: .netjson.net-core

解决方案


这将适用于简单的属性,例如stringsand int、直接引用类型、数组和泛型。尽管泛型只是一个对象,并不表示它是集合还是其他东西。

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using Newtonsoft.Json;

namespace ClassObject
{
    public class Course
    {
        public Collection<Enrollment> EnrollmentsGeneric { get; set; }
        public Enrollment[] EnrollmentsArray { get; set; }
        public int CourseID { get; set; }
        public string Title { get; set; }
        public int Credits { get; set; }
    }

    public class Enrollment
    {
        public int Id { get; set; }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var dict = GetProps(typeof(Course));
            Console.WriteLine(JsonConvert.SerializeObject(dict));
        }

        private static Dictionary<string, object> GetProps(Type type)
        {
            var dict = new Dictionary<string, object> {["name"] = type.Name};
            var props = new Dictionary<string, object>();
            dict["properties"] = props;
            var p = type.GetProperties();

            foreach (var prop in p)
            {
                if (prop.PropertyType.IsPrimitive || prop.PropertyType == typeof(string))
                    props[prop.Name] = prop.PropertyType.ToString();
                else if (prop.PropertyType.IsArray)
                {
                    props[prop.Name] = new[]
                    {
                        GetProps(prop.PropertyType)
                    };
                }
                else if (prop.PropertyType.IsGenericType)
                {
                    var itemType = prop.PropertyType.GetGenericArguments()[0];
                    props[prop.Name] = GetProps(itemType);
                }
                else
                {
                    props[prop.Name] = GetProps(prop.PropertyType);
                }
            }

            return dict;
        }
    }
}

输出

{
    "name": "Course",
    "properties": {
        "EnrollmentsGeneric": {
            "name": "Enrollment",
            "properties": {
                "Id": "System.Int32"
            }
        },
        "EnrollmentsArray": [
            {
                "name": "Enrollment[]",
                "properties": {
                    "Length": "System.Int32",
                    "LongLength": "System.Int64",
                    "Rank": "System.Int32",
                    "SyncRoot": {
                        "name": "Object",
                        "properties": {}
                    },
                    "IsReadOnly": "System.Boolean",
                    "IsFixedSize": "System.Boolean",
                    "IsSyn\r\nchronized": "System.Boolean"
                }
            }
        ],
        "CourseID": "System.Int32",
        "Title": "System.String",
        "Credits": "System.Int32"
    }
}

推荐阅读