【问题标题】:C# deserialize to either list or string [duplicate]C#反序列化为列表或字符串[重复]
【发布时间】:2019-01-23 15:13:24
【问题描述】:

非常接近How to define variable in class to receive either List<string> or string when deserializing JSON?

我更喜欢用python来解析json。没有测试这个,但确定它有效,现在做了几次。 #PythonForLife

import json
str = '{
        "Resource" : ["1", "2"]
       }'
j = json.loads(str)
if ( isinstance( str["Resource"], list ):
        print(str["Resource"][0]) //or do whatever
else:
        print(str["Resource"])    //same

我想知道在 C# 中执行此类操作的最佳做​​法是什么。我有一个类似的模型

public class RootObject 
{
    public IEnumerable<string> Resource {get; set;)
}

这是非常脆弱的,因为它是硬编码的,只处理集合,一旦收到字符串就会中断。我讨厌尝试捕获并使用另一个模型,因为这只是一个属性,在同一个模型中我确实有更多这样的属性。为什么这甚至是一个问题?我在这里链接的是最好/更好/工作的解决方案吗?

【问题讨论】:

标签: c# design-patterns json.net


【解决方案1】:

你应该使用 Dictionary 而不是 List 例如:

    class MyClass
    {
        public void Test()
        {
            var x = @"{'Resource' : ['1', '2']}";

            var r = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(x);
        }
    }

    public static void Main(string[] args)
    {
        var l = new MyClass();
        l.Test();
    }

【讨论】:

    猜你喜欢
    • 2012-05-10
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 2020-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-28
    相关资源
    最近更新 更多