我正在使用Newtonsoft.Json生成以下Json结果。我已经生成了除“属性”之外的大多数输出,并且无法弄清楚该如何执行。结果是客户要求的,不能更改。
预期结果。
{
"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; }
}
谢谢。
答案 0 :(得分:0)
属性需要转换成字典。
class Attribute
{
public string Name { get; set; }
public string Value { get ; set; }
}
(...)
var attributes = new List<Attribute>
{
new Attribute() { Name="Color", Value="Blue" },
new Attribute() { Name= "Weight", Value ="54.4kg" }
};
var d = attributes.ToDictionary(a=> a.Name, a => a.Value);
var json = System.Text.Json.JsonSerializer.Serialize(new { Attributes = d});
Console.WriteLine(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)