我需要将已为其创建模型类的实体框架实体转换为json。
换句话说,我需要从我的实体生成一个json模型。可以吗?
我已经在互联网上搜索过,发现的所有内容都与序列化对象有关,但这并不能满足我的需要,我不能将对象放在json上,我需要将其自身的类转换为JSON。
enter image description here
代码:
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
...
}
答案 0 :(得分:0)
这将与简单的属性(如strings
和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"
}
}