我需要一个比我更聪明的人来指导我在C#中创建一些嵌套字典。我正在尝试在restsharp中创建一个最终类似于这个示例json的帖子:
{
"brandId": 34344,
"collectionId": 5,
"productTypeId": 1,
"identity": {
"sku": "SKU0001",
"ean": "12323423",
"upc": "543534563",
"isbn": "54353453",
"barcode": "45453"
},
"stock": {
"stockTracked": true,
"weight": {
"magnitude": 4324.54
}
},
"financialDetails": {
"taxable": false,
"taxCode": {
"id": 7,
"code": "T20"
}
},
"salesChannels": [
{
"salesChannelName": "Brightpearl",
"productName": "Product B",
"productCondition": "new",
"categories": [
{
"categoryCode": "276"
},
{
"categoryCode": "295"
}
],
"description": {
"languageCode": "en",
"text": "Some description",
"format": "HTML_FRAGMENT"
},
"shortDescription": {
"languageCode": "en",
"text": "Some description",
"format": "HTML_FRAGMENT"
}
}
],
"seasonIds": [
1,
2,
3
],
"nominalCodeStock": "1000",
"nominalCodePurchases": "5000",
"nominalCodeSales": "4000",
"reporting": {
"seasonId": 3,
"categoryId": 295,
"subcategoryId": 298
}
}我以前没有尝试过创建嵌套字典。我的经验更多地局限于:
Dictionary<string, string> values = new Dictionary<string, string>
{
{ "brandid", "1234" },
{ "productTypeId", "11" }
};
string json = JsonConvert.SerializeObject(values);
List<Dictionary<string, string>> ld = new List<Dictionary<string, string>>
{
values
};
request2.AddJsonBody(ld);如果能帮我指明正确的方向,我将不胜感激。
发布于 2021-01-28 00:22:40
我建议您创建对象。如下所示:
public class Portfolio {
public int brandId;
public int collectionId;
public int productTypeId;
public Identity identity
// etc
}
public class Identity {
public string sku;
// etc
}然后创建一个新的portfolio对象,序列化它并通过网络发送它。
var portfolio = new Portfolio
{
// initialize values here
};
string json = JsonConvert.SerializeObject(portfolio);发布于 2021-01-28 00:22:50
这不适用于字典,因为字典值有多种类型(数字、字符串、子字典等)。
我建议创建真正的类型,而不是字典,这最终会减少工作:
// types
public record MyValue(int BrandId, int CollectionId, Identity Identity, [...]){}
public record Identity(string Sku, string, Ean, string Isbn, string Barcode){}
...
// use it
var data = new MyValue(123, 456, new("mysku", "myean", "myisbn", "mybarcode"));
var response = await httpClient.postAsJsonAsync(data);你可以在这里找到文档:
您还必须告诉json序列化程序将C#属性命名样式(AbcDef)转换为驼峰大小写(abcDef),请参阅:ASP.NET Core 3.0 System.Text.Json Camel Case Serialization
请注意,这是c# 9 (.net 5.0)
如果你想做"freestyle",看看dynamic类型的https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/reference-types#the-dynamic-type (观点:不要)
https://stackoverflow.com/questions/65922914
复制相似问题