我正在創建一個返回Json的web api。我出來放看起來是這樣的:如何在Web Api 2中將嵌套列表LINQ到JSON?
[
{
"NodeID":1252,
"CASNumber":"1333-86-4",
"EINECSCode":"215-609-9",
"EUIndex":"215-609-9",
"Duty":"No",
"Prohibited":"No",
"Unwanted":"No",
"IsReach":"No",
"SubstanceName":"Carbon black",
"GroupName":"Renault Complete",
"Portion":0.100000
},
{
"NodeID":1252,
"CASNumber":"1333-86-4",
"EINECSCode":"215-609-9",
"EUIndex":"215-609-9",
"Duty":"No",
"Prohibited":"No",
"Unwanted":"No",
"IsReach":"No",
"SubstanceName":"Carbon black",
"GroupName":"Renault Orange",
"Portion":0.100000
}
]
我試圖創建嵌套的Json像這樣的ouptut:
{
"NodeID":1252,
"CASNumber":"1333-86-4",
"EINECSCode":"215-609-9",
"EUIndex":"215-609-9",
"Duty":"No",
"Prohibited":"No",
"Unwanted":"No",
"IsReach":"No",
"SubstanceName":"Carbon black",
"GroupName":[
{
"name":"Renault Complete"
},
{
"name":"Renault Orange"
}
],
"Portion":0.100000
}
這是我的課:
public class BasicSubstances
{
public int NodeID { get; set; }
public string CASNumber { get; set; }
public string EINECSCode { get; set; }
public string EUIndex { get; set; }
public string Duty { get; set; }
public string Prohibited { get; set; }
public string Unwanted { get; set; }
public string IsReach { get; set; }
public string SubstanceName { get; set; }
public string GroupName { get; set; }
public decimal ?Portion { get; set; }
}
這是我的控制器:
public List<BasicSubstances> GetBasicSubstance(string partNumber, string version, int nodeID, int parentID)
{
IMDSDataContext dc = new IMDSDataContext();
List<BasicSubstances> results = new List<BasicSubstances>();
foreach (spGetBasicSubstanceResult part in dc.spGetBasicSubstance(partNumber, version, nodeID, parentID))
{
results.Add(new BasicSubstances()
{
NodeID = part.NodeID,
CASNumber = part.CASNumber,
EINECSCode = part.EINECSCode,
EUIndex = part.EINECSCode,
Duty = part.Duty,
Prohibited = part.Prohibited,
Unwanted = part.Unwanted,
IsReach = part.ISReach,
SubstanceName = part.SynonymName,
GroupName = part.GroupName,
Portion = part.Portion
});
}
return results;
}
我的Json看起來像第一個輸出,我需要它看起來像第二個輸出。 我完全失去了,任何幫助,將不勝感激。
你怎麼可以肯定,除了'GroupName'所有屬性都會有相同的價值觀? – MaKCbIMKo
它們將始終具有相同的值。在我的存儲過程中它只有一條記錄,我加入了一個表以獲取多個組名列表。 – ChrisPasa
GroupName的類型應該是'public List GroupName {get;組; }'?你不能用字符串創建json數組。你需要在這裏做一些事情'GroupName = part.GroupName,' –
Win