C# 使用Newtonsoft.JSON生成JSON时出现问题
我正在使用Newtonsoft.Json生成以下Json结果。我已经生成了除“Attributes”之外的大部分输出,但我不知道该怎么做。结果由客户端请求,无法更改 预期结果C# 使用Newtonsoft.JSON生成JSON时出现问题,c#,json,json.net,C#,Json,Json.net,我正在使用Newtonsoft.Json生成以下Json结果。我已经生成了除“Attributes”之外的大部分输出,但我不知道该怎么做。结果由客户端请求,无法更改 预期结果 { "TransactionId": "3S76CjmZ3S7", "Environment": "sandbox", "ApiVersion": "1.0", "Error": "", "Warning": "", "Data_response": { "D
{
"TransactionId": "3S76CjmZ3S7",
"Environment": "sandbox",
"ApiVersion": "1.0",
"Error": "",
"Warning": "",
"Data_response": {
"Data_response_data": [{
"Brand": "Genuine",
"Number": "E11106660",
"Description": "DUPLICATE BASE",
"Images": [{
"FileName": "EA10650_STO_FRO_ALL.PNG"
},
{
"FileName": "EA10660_STO_FRO_ALL.png"
}
],
"360Images": [{
"FileName": "EA10660_STO_ALL.zip"
}],
"OriginalStrings": "E11106660",
"Attributes": {
"Color": "Blue",
"Weight": "120lbs",
"Brand": "TRP"
}
}]
}
}
我使用以下代码生成json
JObject jObject = JObject.FromObject(new
{
TransactionId = partRequest.TransactionId,
Environment = partRequest.Environment,
ApiVersion = partRequest.ApiVersion,
Error = "",
Warning = "",
Data_response = new
{
Data_response_data =
from p in Wrapper
orderby p.CompressedNumber
select new
{
Brand = p.Brand,
Number = p.CompressedNumber,
Description = p.Description,
Images =
from d in p.DigitalAssets
orderby d.FileName
select new
{
FileName = d.FileName
},
360Images =
from d in p.DigitalAssets360
orderby d.FileName
select new
{
FileName = d.FileName
},
OriginalStrings = p.CompressedNumber,
Attributes = ???
// I tried this but its throws an exception.
// from d in p.Attributes
// orderby d.Name
// select new
// {
// d.Name = d.Value
//}
}
}
});
属性类
public class Attribute
{
public int Id { get; set; }
public string Name { get; set; }
public string Value { get; set; }
}
提前感谢。属性需要转换为字典 例子
在您的情况下,它可能类似于以下内容
Attributes = (from d in p.Attributes
orderby d.Name
select d).ToDictionary(a=> a.Name, a => a.Value)
多年来,VisualStudio一直能够创建生成或读取JSON所需的类:将有效的JSON复制到剪贴板,然后编辑菜单>>粘贴特殊>>将JSON粘贴为类
{"Attributes":{"Color":"Blue","Weight":"54.4kg"}}
Attributes = (from d in p.Attributes
orderby d.Name
select d).ToDictionary(a=> a.Name, a => a.Value)