C# JSON - 错误:无法使用集合初始值设定项初始化类型(不实现"System.Collection.IEnumerable")



我在调试以下内容时遇到问题(以最简单的方式...我有一组 JSON 的属性,一切都工作到我尝试序列化的程度。我将不胜感激最简单的纠正方法,我必须使用Newtonsoft。 在完整的 C# 代码下方。错误区域正在注释中标记。

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Collections.Generic;
namespace MY_TEST
{
public partial class headers
{
[JsonProperty("RequestID")]
public string myRequest { get; set; } = "someIDhere";
[JsonProperty("CorrelationID")]
public string CorrelationID { get; set; } = "1234567890";
[JsonProperty("Token")]
public string Token { get; set; } = "areallylongstringgoeshereastoken";
[JsonProperty("ContentType")]
public string Content_Type { get; set; } = "application/x-www-form-urlencoded";
}
public partial class access
{
[JsonProperty("allPs")]
public string allPs { get; set; } = "all";
[JsonProperty("availableAccounts")]
public string availableAccounts { get; set; } = "all";
}
public partial class body
{
[JsonProperty("combinedServiceIndicator")]
public bool combinedServiceIndicator { get; set; } = false;
[JsonProperty("frequencyPerDay")]
public int frequencyPerDay { get; set; } = 4;
[JsonProperty("recurringIndicator")]
public bool recurringIndicator { get; set; } = false;
[JsonProperty("validUntil")]
public string validUntil { get; set; } = "2020-12-31";
}
public class Consent    //RootObject
{
[JsonProperty("headers")]
public headers headers { get; set; } 
[JsonProperty("body")]
public body body { get; set; } 
}
class Program
{
static HttpClient client = new HttpClient();
static void ShowConsent(Consent cust_some)
{
Console.WriteLine(cust_some.ToString());
}
static async Task<Uri> CreateConsentAsync(Consent cust_some)
{
HttpResponseMessage response = await client.PostAsJsonAsync("http://myurladdr:8001/me/and/you/api/", cust_some);
ShowConsent(cust_some);
response.EnsureSuccessStatusCode();
return response.Headers.Location;
}
static async Task<Consent> GetConsentAsync(string path)
{
Consent cust_some = null;
HttpResponseMessage response = await client.GetAsync(path);
if (response.IsSuccessStatusCode)
{
cust_some = await response.Content.ReadAsAsync<Consent>();
}
return cust_some;
}
static void Main()
{
RunAsync().GetAwaiter().GetResult();
}
static async Task RunAsync()
{
client.BaseAddress = new Uri("http://myurladdr:8001/me/and/you/api/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
try
{
// >---------- ERROR: Cannot initialize type 'Consent' with a collection initializer because it does not implement 'System.Collection.IEnumerable' ----------<
Consent cust_some = new Consent
{
// Headers
cust_some.headers.myRequest = "someIDhere",
cust_some.headers.CorrelationID = "1234567890",
cust_some.headers.Token = "areallylongstringgoeshereastoken"
cust_some.headers.Content_Type = "application/x-www-form-urlencoded",
// Body
cust_some.body.access.allPs = "all",
cust_some.body.access.availableAccounts = "all",
cust_some.body.combinedServiceIndicator = false,
cust_some.body.frequencyPerDay = 4,
cust_some.body.recurringIndicator = false,
cust_some.body.validUntil = "2020-12-31"
};
// >---------- ERROR ----------<
string json = JsonConvert.SerializeObject(cust_some, Formatting.Indented);
Console.WriteLine(json.ToString());
Console.WriteLine("----------------------------------------------------------");
Console.WriteLine(json);
var url = await CreateConsentAsync(cust_some);
Console.WriteLine($"Created at {url}");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
Console.ReadLine();
}
}
}

Your'e 在自己的初始值设定项中使用标识符名称。例如,在初始值设定项中使用cust_someConsent。您需要删除它们,如下所示:

Consent cust_some = new Consent
{
// Headers
headers = new headers 
{
myRequest = "someIDhere",
CorrelationID = "1234567890",
Token = "areallylongstringgoeshereastoken"
Content_Type = "application/x-www-form-urlencoded"
}
// Body
body = new body
{
access = new access
{
allPs = "all",
availableAccounts = "all"
}
combinedServiceIndicator = false,
frequencyPerDay = 4,  
recurringIndicator = false,
validUntil = "2020-12-31"      
};
}

另外,请注意,根据Microsoft命名约定,除参数名称外的所有标识符都应大写,例如headersbodyaccess等等,无论是类名还是属性名,都应该变成HeadersBodyAccess。你可以在这里阅读它。

在分部类体中,首先在所需的所有属性之前添加以下内容:

[JsonProperty("access")]
public access access { get; internal set; }

现在,[向用户点赞 ****HeyJude**** - 谢谢!

创建
Consent cust_some = new Consent
{
headers = new headers
{
myRequest = "someIDhere",
Correlation_ID = "1234567890",
Token = "areallylongstringgoeshereastoken",
Content_Type = "application/json"    //"application/json; charset=utf-8"
},
body = new body
{
access = new access  //this is how to include access in body
{
allPs = "allAccounts",
availableAccounts = "allAccounts"
},
combinedServiceIndicator = false,
frequencyPerDay = 4,
recurringIndicator = false,
validUntil = "2020-12-31"
}
};

最新更新