【问题标题】:How to pass dictionary with empty array as value如何将空数组作为值传递字典
【发布时间】:2018-11-29 11:13:46
【问题描述】:

我有这个class

public class State{  
        public Dictionary<SecurityType, List<long>> assets { get; set; }
    }

和行动:

[HttpPost]
public virtual ActionResult GetHoldings(State state)
{
        return Json(new HoldingsBL().GetHoldings(state));
}

public enum SecuritySerachType
    {
        Company = 1,
        Security,
    }

当我尝试传递这样的东西时:

{state:{assets :[{"Key":1,"Value":[]}]}}

我在资产属性中找到了空字典。

我已经阅读了this 解决方案,但我不知道如何解决我的问题。

一些简单的解决方案?

编辑: 我尝试像 Oleksii Aza 所说的那样添加 ValueProviderFactory,但是将它与 backingStore 进行比较存在问题(已经存在字典检查,可能用于嵌套对象):

        var d = value as IDictionary<string, object>;
        if (d != null)
        {
            foreach (var entry in d)
            {
                AddToBackingStore(backingStore, MakePropertyKey(prefix, entry.Key), entry.Value);
            }
            return;
        }

所以我仍然坚持这个问题。

【问题讨论】:

  • 什么是SecurityType
  • SecurityType 是枚举
  • 你能包括那个枚举,还包括处理请求的控制器动作吗?
  • 我希望字典映射到类似对象的结构中,例如:{state:{assets :{"1":[]}}}
  • assets 是一个字典数组。

标签: javascript c# asp.net-mvc


【解决方案1】:

尝试对 C# Dictionary 使用类似对象的 JSON 结构,例如:

using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class Program
{
    public enum SecuritySerachType
    {
        Company = 1,
        Security,
    }
    public class State{  
        public Dictionary<SecuritySerachType, List<long>> assets { get; set; }
    }

    public static void Main()
    {
        var state = JsonConvert.DeserializeObject<State>(@"{assets :{""1"":[]}}");
        Console.WriteLine(state.assets[SecuritySerachType.Company].Count);
    }
}

链接到dotnet fiddle

【讨论】:

  • 谢谢。但是当我将它作为类似对象的 json 发送时,资产为空。
  • 如果您使用的是 asp.net core - 这可能是因为您需要指示框架应该从请求正文中获取对象,因此请尝试在 State 状态参数之前添加 [FromBody] 属性
  • 关于 [FromBody] 的更多信息:andrewlock.net/model-binding-json-posts-in-asp-net-core
  • 不,我使用的是 mvc 5。如果我得到字符串,你的解决方案对我有用,并使用 Newtonsoft 进行转换。所以我的问题变成了“如何覆盖默认的 mvc json 反序列化?”
  • 它看起来像在 MVC5 中 - 你需要设置 ValueProviderFactory: stackoverflow.com/questions/23995210/…
猜你喜欢
  • 2018-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-04
  • 2021-09-26
  • 2021-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多