[英]convert objects model to json in c#?
我有一个 object model 我想显示为 json 字符串,例如:
public class SectionD
{
public string InsertID { get; set; }
public int CaseReference { get; set; }
public string AdditionalInfo { get; set; }
public DateTime CreationDate { get; set; }
}
我想将其呈现为 json object,如下所示:
{
"class": "SectionD",
"parameters": [
{
"key": "InsertID",
"type": "string"
},
{
"key": "CaseReference",
"type": "int"
},
{
"key": "AdditionalInfo",
"type": "string"
},
{
"key": "CreationDate",
"type": "DateTime"
}
]
}
数据作为 json 字符串存储在数据库中,我想向将对该数据进行数据库视图的人提供字段和类型的列表。
谷歌提供了很多查询 model 上的内容的点击,但我找不到任何可以查看 object 本身的内容。
谢谢
像这样简单的东西怎么样:
public class ReflectedPropertyInfo
{
[JsonProperty("key")]
public string Key { get; set; }
[JsonProperty("type")]
public string Type { get; set; }
}
public class ReflectJson
{
public static string ReflectIntoJson<T>() where T : class
{
var type = typeof(T);
var className = type.Name;
var props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
var propertyList = new List<ReflectedPropertyInfo>();
foreach (var prop in props)
{
propertyList.Add(new ReflectedPropertyInfo{Key =prop.Name, Type =prop.PropertyType.Name});
}
var result = JsonConvert.SerializeObject(new {@class = className, parameters = propertyList}, Formatting.Indented);
return result;
}
}
正如@dbc 所建议的,它使用反射。 获取类型名称后,它会获取一个属性集合,然后构建一个包含正确格式信息的匿名类型,然后将其序列化。 结果如下所示:
{
"class": "SectionD",
"parameters": [
{
"key": "InsertID",
"type": "String"
},
{
"key": "CaseReference",
"type": "Int32"
},
{
"key": "AdditionalInfo",
"type": "String"
},
{
"key": "CreationDate",
"type": "DateTime"
}
]
}
唯一的区别(我看到)是它使用实际的“Int32”作为整数的类型名称,而不是 C# 别名“int”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.