json - 使用具有对象数组属性的 json 对象从 powershell 调用rest方法

标签 json rest powershell serialization

我试图模仿在 powershell 中的 webapi 调用主体中采用的 C# 类定义,以便我可以使用表示为 json 的该对象调用 Rest 方法。我试图实现的 json 结构的一个示例是:

'{
    "Name" : "Test" ,
    "Items" : [{"Key" : "Test", "Value" : "t2"},{"Key" : "Test2", "Value" : "t3"}]
}'

当设置为 postman 中其余调用的主体时,此 json 有效,如果我用它调用 powershell invokerest-method,则所有字段在 webapi 端都为 null。

这是我当前在 powershell 中的尝试,请注意,Items 实际上是键值对对象的列表。使用下面的代码我只得到 items 中的 1 个项目,其名称和值均为空。

$spec = @{
    Name = 'Test' 
    Items = ,{Name = 'Test', Value = 't2'}, {Name = 'Test2', Value = 't3'}
}

invoke-restmethod $someurl  -Method:POST -body $spec | Write-Host

我相当确定我遗漏了 powershell 对象上项目的数组声明中的一些重要内容。

这是剩下的方法:

   [HttpPost]
    [Route("addorupdateitem")]
    public void Add([FromBody] ItemConfigurationDto itemconfig)
    {
        var serializeObject = Newtonsoft.Json.JsonConvert.SerializeObject(context);
        Debug.WriteLine(serializeObject);
    }

和对象

public class ItemConfigurationDto
{
    public string Name { get; set; }
    public List<Item> Items { get; set; } = new List<Item>();
}

public class Item
{
    public string Name { get; set; }
    public string Value { get; set; }
}

最佳答案

已解决问题。我必须设置 -ContentType 'application/json' 并将对象转换为 json,然后再将其添加到正文中。

关于json - 使用具有对象数组属性的 json 对象从 powershell 调用rest方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33526321/

相关文章:

javascript - 从数组中的另一个对象更新数组中的对象

json - 将 JSON 解码为结构

wcf - 从WCF服务生成RESTful API文档

oracle - 在 powershell 中处理 null

java - 无法在 AsyncTask 中获取经纬度

json - Swift 解码嵌套的 JSON

java - Facebook:获取 session key 时签名不正确 (104)

java - Web 服务接收对象时子对象丢失

bash - Bash 上的反勾号的 cmd/PowerShell 等价物是什么?

powershell - AutohotKey中的Powershell无法正常工作