mardi 24 mars 2015

How to Customize root element Name xml and json serialisation?


Vote count:

0




I generate xml and json result for my WEB APi application,I try to this result into customize root element name. but have some issues. Here is the Class for the Result



[XmlRoot("country")]
[JsonObject(Title = "country")]

public class CountryData
{
[XmlElement(ElementName = "iso_code")]
[JsonProperty(PropertyName = "iso_code")]
public string IsoCode { get; set; }

[XmlElement(ElementName = "fips_code")]
[JsonProperty(PropertyName = "fips_code")]
public string FipsCode { get; set; }

[XmlElement(ElementName = "name")]
[JsonProperty(PropertyName = "name")]
public string Name { get; set; }

[XmlElement(ElementName = "region_id")]
[JsonProperty(PropertyName = "region_id")]
public string RegionId { get; set; }
}
public class CountryList
{
[XmlArray("countries")]
[JsonProperty(PropertyName = "countries")]
public List<CountryData> Country { get; set; }
public CountryList()
{
Country = new List<CountryData>();
}
}


I use customXMLFormatter class instead of xmlFormatter and Use the Method



public override Task WriteToStreamAsync(Type type, object value,
Stream writeStream, System.Net.Http.HttpContent content,
System.Net.TransportContext transportContext)
{
return Task.Factory.StartNew(() =>
{
var xns = new XmlSerializerNamespaces();
var serializer = new XmlSerializer(type);
xns.Add(string.Empty, string.Empty);
serializer.Serialize(writeStream, value, xns);
});
}


I try to create xml result as shown below



<response>
<response_item>
<countries>
<country>
<iso_code>AF</iso_code>
<fips_code>AF</fips_code>
<name>Afghanistan</name>
<region_id>ASIA</region_id>
</country>
</countries>
</response_item>
</response>


and Json



[{"countries":[{"iso_code":"AF","fips_code":"AF","name":"Afghanistan","region_id":"ASIA"}]}]


I get the xml as Shown Below



<CountryList>
<countries>
<CountryData>
<iso_code>AE</iso_code>
<fips_code>AE</fips_code>
<name>United Arab Emirates</name>
<region_id>ASIA</region_id>
</CountryData>
</countries>
</CountryList>


and Json{"countries":[{"iso_code":"AE","fips_code":"AE","name":"United Arab Emirates","region_id":"ASIA"}]}


How can I generate my actual output? <response><response_item> tag is need for all my xml results.



asked 48 secs ago







How to Customize root element Name xml and json serialisation?

Aucun commentaire:

Enregistrer un commentaire