I'm atempting to use the same class structure for a web api function which should return either json or xml - whichever the client requires.
However, the structure requirements are a little different from json to xml.
The XML should look like this:
<prtg>
<result>
<channel>First channel</channel>
<value>10</value>
</result>
<result>
<channel>Second channel</channel>
<value>20</value>
</result>
</prtg>
And the JSON should look like this
{
"prtg": {
"result": [
{
"channel": "First channel",
"value": "10"
},
{
"channel": "Second channel",
"value": "20"
}
]
}
}
I'm unable to make this interchangable.
The classes I'm serializing are thus:
[DataContract]
public class PrtgModel
{
[DataMember]
public Prtg Prtg { get; set; } = new Prtg();
}
//[JsonObject(NamingStrategyType = typeof(Newtonsoft.Json.Serialization.CamelCaseNamingStrategy))]
[DataContract]
public class Prtg
{
[DataMember]
public IList<PrtgResult> Result { get; set; } = new List<PrtgResult>();
}
//[JsonObject(NamingStrategyType = typeof(Newtonsoft.Json.Serialization.CamelCaseNamingStrategy))]
[DataContract]
public class PrtgResult
{
[DataMember]
public string Channel { get; set; }
[DataMember]
public string Value { get; set; }
//[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[DataMember]
public int? LimitMaxError { get; set; }
//[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[DataMember]
public int? LimitMinError { get; set; }
//[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[DataMember]
public string LimitErrorMsg { get; set; }
//[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
[DataMember]
public int? LimitMode { get; set; } // 0=no, 1=yes
}
This renders the correct JSON, but if i request XML I get the PrtgResult
element also. Looking at https://learn.microsoft.com/en-us/dotnet/standard/serialization/controlling-xml-serialization-using-attributes#controlling-serialization-of-classes-using-xmlrootattribute-and-xmltypeattribute doesn't quite show how to flatten the array the way i require.
Is this really possible with annotation without completely overriding the xml generation?