我正在开发一个返回JSON文件的WEB API。我希望我的JSON像这样:
{
"PensionDistribution": [{
"rows": [{
"uniqueName": "Age"
}]
},
{
"columns": [{
"uniqueName": "Year"
},
{
"uniqueName": "Type"
}]
},
{
"measures": [{
"uniqueName": "AgentID",
"aggregation": "count"
}]
},
{
"fields": {
"Age": {
"type": "number",
"caption": "Age"
},
"AgentComputedCompleteName": {
"type": "string",
"caption": "Nom complet encodé de l'agent"
},
"AgentID": {
"type": "number",
"caption": "ID Agent"
},
"MatriculeAgent": {
"type": "string",
"caption": "Matricule agent"
},
"Type": {
"type": "string",
"caption": "Type"
},
"TypeKey": {
"type": "string",
"caption": "Type clé"
},
"Year": {
"type": "string",
"caption": "Année"
}
}
}]
}
所以我创建了将我的数据库数据转换为我的JSON的类:
public class PivotConfigData
{
public class Report
{
public string Name { get; set; }
public List<Row> Rows { get; set; }
public List<Column> Columns { get; set; }
public List<Measure> Measures { get; set; }
public List<Field> Fields { get; set; }
public Report()
{
Name = "";
Rows = new List<Row>();
Columns = new List<Column>();
Measures = new List<Measure>();
Fields = new List<Field>();
}
}
public class Row
{
public string UniqueName { get; set; }
}
public class Column
{
public string UniqueName { get; set; }
}
public class Measure
{
public string UniqueName { get; set; }
public string Aggregation { get; set; }
}
public class Field
{
public string Name { get; set; }
public FieldAttributes Attributes { get; set; }
}
public class FieldAttributes
{
public string Type { get; set; }
public string Caption { get; set; }
}
}
通过使用这个,我得到一个像这样的JSON文件:
{
"Name": "PensionDistribution",
"Rows": [{
"UniqueName": "Age"
}],
"Columns": [{
"UniqueName": "Year"
},
{
"UniqueName": "Type"
}],
"Measures": [{
"UniqueName": "AgentID",
"Aggregation": "count"
}],
"Fields": [{
"Name": "Age",
"Attributes": {
"Type": "number",
"Caption": "Age"
}
},
{
"Name": "AgentComputedCompleteName",
"Attributes": {
"Type": "string",
"Caption": "Nom complet encodé de l'agent"
}
},
{
"Name": "AgentID",
"Attributes": {
"Type": "number",
"Caption": "ID Agent"
}
},
{
"Name": "MatriculeAgent",
"Attributes": {
"Type": "string",
"Caption": "Matricule agent"
}
},
{
"Name": "Type",
"Attributes": {
"Type": "string",
"Caption": "Type"
}
},
{
"Name": "TypeKey",
"Attributes": {
"Type": "string",
"Caption": "Type clé"
}
},
{
"Name": "Year",
"Attributes": {
"Type": "string",
"Caption": "Année"
}
}]
}
正如你所看到的,它在“PensionDistribution”之前添加了“名称”:但这不是什么大问题。这是“Fields”集合的一个问题,因为它添加了“Name”和“Attributes”,如何删除或隐藏这些属性名称?我试图在我的财产之前添加[JsonProperty(“”)],但它取代了“Name”:by“”:这不是我想要的。
是的,有人可以帮帮我吗?答案 0 :(得分:1)
使用不需要的属性JsonIgnore。
对于更改属性名称,请使用[JsonProperty(PropertyName = "NewName")]
。
答案 1 :(得分:1)
您可以使用.NET Framework的常规序列化属性(DataMemberAttribute
,DataContractAttribute
等),而不是使用JSON.NET中的属性(使您的代码依赖于它)。
要忽略/删除JSON中的属性,您可以使用IgnoreDataMemberAttribute
来装饰它们。
[DataContract]
public class Field
{
[IgnoreDataMember]
public string Name { get; set; }
[DataMember]
public FieldAttributes Attributes { get; set; }
}