.net - 将 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
...
}
解决方案
这将适用于简单的属性,例如strings
and 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"
}
}
推荐阅读
- node.js - 我们可以使用 node js 作为服务器从另一个机器人向机器人发送消息吗?
- angular - 如何使用 ionic 4 检测输入中的@?
- python - 找不到用于读取 csv 的正确编解码器
- c# - Linq,为什么不运行将查询拆分为单独的方法
- c# - 如何从 .NET 缓存中删除单个 HTTP 响应?
- c++ - Windows 不信任自签名驱动程序(使用自定义自签名 CA)
- java - 我应该如何获得相关实体?
- javascript - 由于(可能)错误的 bash 脚本导致一些奇怪的错误
- c# - 从 SMO TransferData 方法调用 CREATE INDEX 120 秒后“等待操作超时”
- python - 深度学习模型没有泛化