gpt4 book ai didi

c# - 如何将类元数据转换为 JSON 字符串

转载 作者:行者123 更新时间:2023-11-30 13:36:20 25 4
gpt4 key购买 nike

如何生成 Class 元数据的 JSON。

例如。

C# 类

public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public bool IsActive { get; set; }
public Description Description { get; set; }
}

public class Description
{
public string Content { get; set; }
public string ShortContent { get; set; }
}

JSON

[
{
"PropertyName" : "Id",
"Type" : "Int",
"IsPrimitive" : true
},
{
"PropertyName" : "Name",
"Type" : "string",
"IsPrimitive" : true
},
{
"PropertyName" : "IsActive",
"Type" : "bool",
"IsPrimitive" : true
},
{
"PropertyName" : "Description",
"Type" : "Description",
"IsPrimitive" : false
"Properties" : {
{
"PropertyName" : "Content",
"Type" : "string",
"IsPrimitive" : true
},
{
"PropertyName" : "ShortContent",
"Type" : "string",
"IsPrimitive" : true
}
}
},
]

最佳答案

如果您定义一个将映射您的 Json 模型的类:

public class PropertyDescription
{
public string PropertyName { get; set; }

public string Type { get; set; }

public bool IsPrimitive { get; set; }

public IEnumerable<PropertyDescription> Properties { get; set; }
}

然后创建一个递归读取对象属性的函数:

public static List<PropertyDescription> ReadObject(Type type)
{
var propertyDescriptions = new List<PropertyDescription>();
foreach (var propertyInfo in type.GetProperties())
{
var propertyDescription = new PropertyDescription
{
PropertyName = propertyInfo.Name,
Type = propertyInfo.PropertyType.Name
};

if (!propertyDescription.IsPrimitive
// String is not a primitive type
&& propertyInfo.PropertyType != typeof (string))
{
propertyDescription.IsPrimitive = false;
propertyDescription.Properties = ReadObject(propertyInfo.PropertyType);
}
else
{
propertyDescription.IsPrimitive = true;
}
propertyDescriptions.Add(propertyDescription);
}

return propertyDescriptions;
}

您可以使用 Json.Net序列化此函数的结果:

var result = ReadObject(typeof(Product));
var json = JsonConvert.SerializeObject(result);

编辑:基于@AmitKumarGhosh 回答的 Linq 解决方案:

public static IEnumerable<object> ReadType(Type type)
{
return type.GetProperties().Select(a => new
{
PropertyName = a.Name,
Type = a.PropertyType.Name,
IsPrimitive = a.PropertyType.IsPrimitive && a.PropertyType != typeof (string),
Properties = (a.PropertyType.IsPrimitive && a.PropertyType != typeof(string)) ? null : ReadType(a.PropertyType)
}).ToList();
}

...

var result = ReadType(typeof(Product));
json = JsonConvert.SerializeObject(result);

关于c# - 如何将类元数据转换为 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35222366/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com