在 C# 中将对象模型转换为 json?

convert objects model to json in c#?

我有一个要显示为 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 字符串的形式存储在数据库中,我想向将对该数据进行数据库查看的人员提供字段和类型列表。

google提供了很多查询模型上内容的命中,但是我找不到任何东西来查看对象本身。

谢谢

像这样简单的东西怎么样:

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”。