使用C#和RestSharp正确设置嵌套字典
我需要一个比我更聪明的人来指导我用C#创建一些嵌套字典。我正试图在restsharp中创建一个帖子,最终类似于以下示例json:使用C#和RestSharp正确设置嵌套字典,c#,restsharp,C#,Restsharp,我需要一个比我更聪明的人来指导我用C#创建一些嵌套字典。我正试图在restsharp中创建一个帖子,最终类似于以下示例json: { "brandId": 34344, "collectionId": 5, "productTypeId": 1, "identity": { "sku": "SKU0001", &q
{
"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);
字典值=新字典
{
{“brandid”,“1234”},
{“productTypeId”,“11”}
};
字符串json=JsonConvert.SerializeObject(值);
列表ld=新列表
{
价值观
};
请求2.AddJsonBody(ld);
如果您能帮我指出正确的方向,我将不胜感激。我建议您创建该对象。大概是这样的:
public class Portfolio {
public int brandId;
public int collectionId;
public int productTypeId;
public Identity identity
// etc
}
public class Identity {
public string sku;
// etc
}
然后创建一个新的公文包对象,将其序列化并通过网络发送
var portfolio = new Portfolio
{
// initialize values here
};
string json = JsonConvert.SerializeObject(portfolio);
这对字典不起作用,因为字典值有多种类型(数字、字符串、子字典等) 我建议创建真正的类型,而不是字典,这最终会减少工作量:
// 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);
您可以在此处找到文档:
如果你想做“自由式”,看看
dynamic
类型(意见:不要)为什么要使用嵌套的Disctionary?您可以使用对象对数据建模,然后序列化对象。@AthanasiosKataras您可能是对的。这将是一个更好的方法。我在下面的答案中添加了一个高级示例!干杯