【问题标题】:Deserialize a lot of properties from JSON从 JSON 中反序列化很多属性
【发布时间】:2022-09-26 15:38:34
【问题描述】:

这是 JSON 文件的示例:

{
    \"Object\": {
        \"series\": {
            \"transformation\": \"\",
            \"source\": \"series\",
            \"default\": \"\"
        },
        \"latitude\": {
            \"transformation\": \"\",
            \"source\": \"lat\",
            \"default\": \"\"
        },
        \"longitude\": {
            \"transformation\": \"\",
            \"source\": \"long\",
            \"default\": \"\"
        }
   }
}

我目前使用JsonConvert.DesirializeT()进行反序列化的课程

internal class ImportedObjects
{
        [JsonProperty(\"Object\")]
        public ImportedSubProperties ImportedObject { get; set; }

        internal class ImportedSubProperties : ImportedObjects
        {
            [JsonProperty(\"series\")]
            public ImportedProperties series { get; set; }

            [JsonProperty(\"latitude\")]
            public ImportedProperties latitude { get; set; }

            [JsonProperty(\"longitude\")]
            public ImportedProperties longitude { get; set; }
        }
}

internal class ImportedProperties
{
        public string Transformation { get; set; }
        public string Source { get; set; }
        public string Default { get; set; }
}

当前解析代码:

using (StreamReader r = new StreamReader(file))
{
    string json = r.ReadToEnd();
    MappingObjects = JsonConvert.DeserializeObject<ImportedObjects>(json);
}

当只有 3 个属性(系列、纬度、经度)时,一切看起来都很好,但在实际文件中,“经度”(X、Y、大小……)之后至少有 50 个属性。我的问题:是否可以在不创建额外 50 个属性的情况下优化反序列化?最好将所有内容直接存储到字典中。

    标签: c# json .net parsing


    【解决方案1】:

    您可以使用Dictionary&lt;&gt;

    internal class ImportedObjects
    {
         public Dictionary<string,ImportedProperties> Object { get; set;}
    }
    
    internal class ImportedProperties
    {
            public string Transformation { get; set; }
            public string Source { get; set; }
            public string Default { get; set; }
    }
    

    【讨论】:

      【解决方案2】:

      您应该能够反序列化为字典:

      internal class ImportedObjects
      {
              [JsonProperty("Object")]
              public Dictionary<string, ImportedProperties> ImportedObject { get; set; }
      
      ...
      
      JsonConvert.DeserializeObject<ImportedObjects>(json);
      

      【讨论】:

        猜你喜欢
        • 2014-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多