在c#中将对象模型转换为json?
我有一个要显示为json字符串的对象模型,例如:在c#中将对象模型转换为json?,c#,json,object,model,C#,Json,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对象,如下所示
public class SectionD
{
public string InsertID { get; set; }
public int CaseReference { get; set; }
public string AdditionalInfo { get; set; }
public DateTime CreationDate { get; set; }
}
我想将其表示为一个json对象,如下所示:
{
"class": "SectionD",
"parameters": [
{
"key": "InsertID",
"type": "string"
},
{
"key": "CaseReference",
"type": "int"
},
{
"key": "AdditionalInfo",
"type": "string"
},
{
"key": "CreationDate",
"type": "DateTime"
}
]
}
数据以json字符串的形式存储在数据库中,我想向对该数据进行数据库查看的人提供一个字段和类型列表
谷歌提供了很多点击量来查询模型上的内容,但是我找不到任何东西来查看对象本身
谢谢简单点,比如:
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;
}
}
唯一的区别(我看到的)是它使用实际的“Int32”作为整数的类型名,而不是C#别名“int”。使用json模式可能更好-您可以通过以下方式完成此操作,如图所示,或者直接使用json.NET的契约解析器,如图所示:。这就是你的全部要求吗?
{
"class": "SectionD",
"parameters": [
{
"key": "InsertID",
"type": "String"
},
{
"key": "CaseReference",
"type": "Int32"
},
{
"key": "AdditionalInfo",
"type": "String"
},
{
"key": "CreationDate",
"type": "DateTime"
}
]
}