【问题标题】:convert objects model to json in c#?在c#中将对象模型转换为json?
【发布时间】:2021-02-04 17:31:07
【问题描述】:

我有一个对象模型想要显示为 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 提供了很多用于查询模型内容的命中,但我找不到任何可以查看对象本身的内容。

谢谢

【问题讨论】:

标签: c# json object model


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 2022-10-22
    相关资源
    最近更新 更多