Could Not Serialize object to .\Sample.xml - c#

I am trying to serialize an object to xml, and I have the error below:
: Could Not Serialize object to .\Sample.xml
The inner exception is:
There was an error reflecting type 'SiteProvisioningFramework.Entities.SiteDefinition'.
The serializing code is:
static void Main(string[] args)
{
var siteDefinition = new SiteDefinition();
siteDefinition.Name = "ContosoIntranet";
siteDefinition.Version = "1.0.0.0";
siteDefinition.MasterPages = new List<SiteProvisioningFramework.MasterPage>()
{
new MasterPage(){
Name="seattle.master",
ServerFolder ="_catalogs/ContosoIntranet/",
UIVersion = "15",
Url="",
LocalFolder = ".MasterPages/seattle.master"
}
};
Utilities.XmlHelper.ObjectToXml(siteDefinition, #".\Sample.xml");
}
public static void ObjectToXml(object obj, string path_to_xml)
{
//serialize and persist it to it's file
try
{
System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(obj.GetType());
FileStream fs = File.Open(
path_to_xml,
FileMode.OpenOrCreate,
FileAccess.Write,
FileShare.ReadWrite);
ser.Serialize(fs, obj);
}
catch (Exception ex)
{
throw new Exception(
"Could Not Serialize object to " + path_to_xml,
ex);
}
}
The classes are:
public class SiteDefinition
{
[XmlAttribute ()]
public string Name { get; set; }
[XmlAttribute()]
public string Version { get; set; }
public List<MasterPage> MasterPages { get; set; }
public List<File> Files { get; set; }
public List<PageLayout> PageLayouts { get; set; }
public List<Feature> Features { get; set; }
public List<ContentType> ContentTypes { get; set; }
public List<StyleSheet> StyleSheets { get; set; }
}
public class MasterPage : File
{
[XmlAttribute()]
public string UIVersion { get; set; }
[XmlAttribute()]
public string MasterPageDescription { get; set; }
}
public class File
{
[XmlAttribute()]
public string Url { get; set; }
[XmlAttribute()]
public string Name { get; set; }
[XmlAttribute()]
public string LocalFolder { get; set; }
[XmlAttribute()]
public string ServerFolder { get; set; }
}
public class Field
{
public string Guid { get; set; }
public string Name { get; set; }
public string GroupName { get; set; }
}
public class Feature
{
public string Guid { get; set; }
}
public class ContentType
{
public string Guid { get; set; }
public string Name { get; set; }
public string GroupName { get; set; }
public List<Field> Fields { get; set; }
}
public class List
{
public List<ContentType> ContentTypes { get; set; }
public string Name { get; set; }
}
public class PageLayout : File
{
public string UIVersion { get; set; }
public string MasterPageDescription { get; set; }
}
public class StyleSheet : File
{
public string Name { get; set; }
}
public class Theme
{
public string Name { get; set; }
public string ColorFilePath { get; set; }
public string FontFilePath { get; set; }
public string BackgroundImagePath { get; set; }
public MasterPage MasterPage { get; set; }
}
any idea?

The error lies with one property in your SiteDefinition class -
public List<ContentType> ContentTypes { get; set; }
A System.Net.Mime.ContentType apparently can't be serialized. If you put an XmlIgnore attribute on it, the code runs fine.
[XmlIgnore]
public List<ContentType> ContentTypes { get; set; }
Edit:
Your ContentType is a custom class - so that is not it. But your Name property in your StyleSheet class is hiding the exact same property in the class that it inherits from (File) - this is causing the serialization error.

Related

Error deserializing XML file into C# class of objects

I have this xml file:
<?xml version="1.0" encoding="UTF-8"?>
<pippo:Response xmlns:pippo="http://pippoonboarding.eu">
<pippo:Header>
<pippo:FileId>123</pippo:FileId>
<pippo:SenderId>1234</pippo:SenderId>
<pippo:ProcessingDate>20210630</pippo:ProcessingDate>
<pippo:ProcessingTime>1130</pippo:ProcessingTime>
<pippo:ResponseCode>OK</pippo:ResponseCode>
</pippo:Header>
<pippo:CompanyResponse>
<pippo:SellerId>1234</pippo:SellerId>
<pippo:SellerContractCode />
<pippo:VATNumber>123456</pippo:VATNumber>
<pippo:ResponseCode>KO</pippo:ResponseCode>
<pippo:PippoCompanyCode />
<pippo:ResponseDetails>
<pippo:Entity>ciaone</pippo:Entity>
<pippo:ProgressiveNumber>1</pippo:ProgressiveNumber>
<pippo:PippoShopCode />
<pippo:TerminalId />
<pippo:FieldName />
<pippo:ErrorType>DDD</pippo:ErrorType>
<pippo:ErrorCode>1234</pippo:ErrorCode>
<pippo:ErrorDescription>test</pippo:ErrorDescription>
</pippo:ResponseDetails>
</pippo:CompanyResponse>
</pippo:Response>
and I want to deserialize into my class:
public class XmlDeserializer
{
[Serializable, XmlRoot("pippo:Response xmlns:pippo=\"http://pippoonboarding.eu\"")]
public class Root
{
public string Response { get; set; }
//[XmlElement(ElementName = "Header")]
public Header Header { get; set; }
public CompanyResponse CompanyResponse { get; set; }
}
public class Header
{
public string FileId { get; set; }
public string SenderId { get; set; }
public string ProcessingDate { get; set; }
public string ProcessingTime { get; set; }
public string ResponseCode { get; set; }
}
public class CompanyResponse
{
public string SellerId { get; set; }
public int SellerContractCode { get; set; }
public int VATNumber { get; set; }
public int ResponseCode { get; set; }
public int PippoCompanyCode { get; set; }
public ResponseDetails ResponseDetails { get; set; }
}
public class ResponseDetails
{
public string Entity { get; set; }
public string ProgressiveNumber { get; set; }
public string PippoShopCode { get; set; }
public string TerminalId { get; set; }
public string FieldName { get; set; }
public string ErrorType { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
}
but I receive this error:
There is an error in XML document (2, 2).
<Response xmlns='http://pippoonboarding.eu'> was not expected.
What does the error mean? What should I do?
Following code works. Had to change a few integers to strings in class definitions.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace ConsoleApplication2
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
XmlDeserializer response = new XmlDeserializer(FILENAME);
}
}
public class XmlDeserializer
{
public XmlDeserializer(string filename)
{
XmlReader reader = XmlReader.Create(filename);
XmlSerializer serializer = new XmlSerializer(typeof(Root));
Root response = (Root)serializer.Deserialize(reader);
}
[XmlRoot(ElementName = "Response", Namespace = "http://pippoonboarding.eu")]
public class Root
{
public string Response { get; set; }
//[XmlElement(ElementName = "Header")]
public Header Header { get; set; }
public CompanyResponse CompanyResponse { get; set; }
}
public class Header
{
public string FileId { get; set; }
public string SenderId { get; set; }
public string ProcessingDate { get; set; }
public string ProcessingTime { get; set; }
public string ResponseCode { get; set; }
}
public class CompanyResponse
{
public string SellerId { get; set; }
public string SellerContractCode { get; set; }
public int VATNumber { get; set; }
public string ResponseCode { get; set; }
public string PippoCompanyCode { get; set; }
public ResponseDetails ResponseDetails { get; set; }
}
public class ResponseDetails
{
public string Entity { get; set; }
public string ProgressiveNumber { get; set; }
public string PippoShopCode { get; set; }
public string TerminalId { get; set; }
public string FieldName { get; set; }
public string ErrorType { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
}
}
}

How can I XML Serialize an object that is the base class and has 4 derived classes

So this is my base class:
[Serializable]
public class Clienti:IComparable
{
public String Nume { get; set; }
public String Prenume { get; set; }
public String Adresa { get; set; }
public long CNP { get; set; }
public String SerieBuletin { get; set; }
public String DataNasterii { get; set; }
public String Telefon { get; set; }
public List<Asigurari> listaAsigurari { get; set; }
}
The class that is the List in Clienti is this one:
[Serializable]
public abstract class Asigurari
{
//atribute cu AutoProperties
public String denumireBun { get; set; }
public String numeAsigurator { get; set; }
public String locatieBun { get; set; }
public float sumaAsigurare { get; set; }
public String dataPolitaInceput { get; set; }
public String dataPolitaSfarsit { get; set; }
public String tipAsigurare { get; set; }
}
and practically this one is the base clase for the other 4 classes:
[Serializable]
public class Automobil:Asigurari
{
public String marca { get; set; }
public String model { get; set; }
public String numarImatriculare { get; set; }
public String serieSasiu { get; set; }
public int capacitateCilindrica { get; set; }
public int numarLocuri { get; set; }
public int masaMaximaAdmisa { get; set; }
}
[Serializable]
public class AlteBunuri:Asigurari
{
public String detaliiBun { get; set; }
}
[Serializable]
public class Locuinta:Asigurari
{
public String Adresa { get; set; }
public tipLocuinta tip { get; set; }
public int numarNiveluri { get; set; }
public float suprafataTotala { get; set; }
public float suprafataUtilizabila { get; set; }
public int numarCamere { get; set; }
}
[Serializable]
public class Viata:Asigurari
{
public int varsta { get; set; }
public String grupaSangvina { get; set; }
public float inaltime { get; set; }
public float greutate { get; set; }
public Gen gen { get; set; }
public StareCivila stareCivila { get; set; }
}
every class of these 4 has contructor with params, and without.
And my code for XML Serialise and Deserialize is this :
private void xMLToolStripMenuItem_Click(object sender, EventArgs e)
{
XmlSerializer xmlSerializer = new XmlSerializer(typeof(List<Clienti>),new Type[] { typeof(Asigurari)});
System.IO.FileStream fs = File.Create("lista.xml");
xmlSerializer.Serialize(fs, listaClienti);
fs.Close();
MessageBox.Show("Serializare cu succes in lista.xml");
}
private void coleToolStripMenuItem_Click(object sender, EventArgs e)
{
XmlSerializer xml = new XmlSerializer(typeof(List<Clienti>));
try
{
FileStream fs = File.OpenRead("lista.xml");
listaClienti = xml.Deserialize(fs) as List<Clienti>;
fs.Close();
populareLV();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
and I get this error:
Sorry for the long post or if I did not explain it so well.
As the exception message says, you need to let the base class know of derived types like
[XmlInclude(typeof(Automobil))]
public abstract class Asigurari
{
//atribute cu AutoProperties
public String denumireBun { get; set; }
public String numeAsigurator { get; set; }
public String locatieBun { get; set; }
public float sumaAsigurare { get; set; }
public String dataPolitaInceput { get; set; }
public String dataPolitaSfarsit { get; set; }
public String tipAsigurare { get; set; }
}
Use the XmlIncludeAttribute when you call the Serialize or Deserialize method of the XmlSerializer class.
You should specify the [XmlInclude(typeof(DerivedType1), XmlInclude(typeof(DerivedType2)...] attributes on the base class

Json string deserialization C#

I have this json
and i want to deserialize it so I can get each object's value for example:
"icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpouLWzKjhzw8zFdC5K092kl5SClMj3PLXFhGpC_Pp8j-3I4IG7i1Hn_UI-Nmj3ItDGe1BoN1mCr1G4xL_vhMS8tcmcn3JhuihwsHvbzQv3309k3tBw8A",
The problem is I can make the class(es) that I need so I can deserialize the json because the json string has nested objects.
I used json2csharp to help me generate classes. After some merging and cleaning up, this is what I got:
public class InventoryItem
{
public string id { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string amount { get; set; }
public int pos { get; set; }
}
public class AppData
{
public string def_index { get; set; }
public int? is_itemset_name { get; set; }
public int? limited { get; set; }
}
public class Description
{
public string type { get; set; }
public string value { get; set; }
public string color { get; set; }
public AppData app_data { get; set; }
}
public class Action
{
public string name { get; set; }
public string link { get; set; }
}
public class Tag
{
public string internal_name { get; set; }
public string name { get; set; }
public string category { get; set; }
public string category_name { get; set; }
public string color { get; set; }
}
public class RgDescription
{
public string appid { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string icon_url { get; set; }
public string icon_url_large { get; set; }
public string icon_drag_url { get; set; }
public string name { get; set; }
public string market_hash_name { get; set; }
public string market_name { get; set; }
public string name_color { get; set; }
public string background_color { get; set; }
public string type { get; set; }
public int tradable { get; set; }
public int marketable { get; set; }
public int commodity { get; set; }
public string market_tradable_restriction { get; set; }
public List<Description> descriptions { get; set; }
public List<Action> actions { get; set; }
public List<Action> market_actions { get; set; }
public List<Tag> tags { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public IDictionary<string, InventoryItem> rgInventory { get; set; }
public List<object> rgCurrency { get; set; }
public IDictionary<string, RgDescription> rgDescriptions { get; set; }
public bool more { get; set; }
public bool more_start { get; set; }
}
These appear to work correctly, you can deserialize and serialize with code like this:
var obj = JsonConvert.DeserializeObject<RootObject>(oldString);
Console.WriteLine(obj.rgDescriptions["310776560_302028390"].icon_url); // e.g.
var newString = JsonConvert.SerializeObject(obj,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// null value handling is optional, the above makes it a little more like the source string

Generate C# object from Json string and parse Json string to generated object

I am trying to generate C# class using the JSON string from here http://json2csharp.com/ this works fine. But I can't parse the JSON to the object generated by the website.
Here is the JSON string
{
"searchParameters":{
"key":"**********",
"system":"urn:oid:.8"
},
"message":" found one Person matching your search criteria.",
"_links":{
"self":{
"href":"https://integration.rest.api.test.com/v1/person?key=123456&system=12.4.34.."
}
},
"_embedded":{
"person":[
{
"details":{
"address":[
{
"line":["5554519 testdr"],
"city":"testland",
"state":"TT",
"zip":"12345",
"period":{
"start":"2003-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"name":[
{
"use":"usual",
"family":["BC"],
"given":["TWO"],
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"gender":{
"code":"M",
"display":"Male"
},
"birthDate":"9999-02-03T00:00:00Z",
"identifier":[
{
"use":"unspecified",
"system":"urn:oid:2.19.8",
"key":"",
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"telecom":[
{
"system":"email",
"value":"test#test.com",
"use":"unspecified",
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"photo":[
{
"content":{
"contentType":"image/jpeg",
"language":"",
"data":"",
"size":0,
"hash":"",
"title":"My Picture"
}
}
]
},
"enrolled":true,
"enrollmentSummary":{
"dateEnrolled":"9999-02-07T21:39:11.174Z",
"enroller":"test Support"
},
"_links":{
"self":{
"href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc"
},
"unenroll":{
"href":"https://integration.rest.api.test.com/v1/person/1b018dc4-182d-4296-90cc-/unenroll"
},
"personLink":{
"href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc-953c/personLink"
},
"personMatch":{
"href":"https://integration.rest.api.commonwellalliance.org/v1/person/-182d-4296-90cc-/personMatch?orgId="
}
}
}
]
}
}
Here is the code I use to convert to the object.
JavaScriptSerializer js = new JavaScriptSerializer();
var xx = (PersonsearchVM)js.Deserialize(jsonstr, typeof(PersonsearchVM));
Is there any other wat to generate the object and parse?
I think you have some invalid characters in your JSON string. Run it through a validator and add the necessary escape characters.
http://jsonlint.com/
You aren't casting it to the right object. Cast it to the type RootObject.
Eg
JavaScriptSerializer js = new JavaScriptSerializer();
var xx = (RootObject)js.Deserialize(jsonstr, typeof(RootObject));
The code that json 2 csharp creates is this:
public class SearchParameters
{
public string key { get; set; }
public string system { get; set; }
}
public class Self
{
public string href { get; set; }
}
public class LinKs
{
public Self self { get; set; }
}
public class Period
{
public string start { get; set; }
public string end { get; set; }
}
public class Address
{
public List<string> line { get; set; }
public string city { get; set; }
public string __invalid_name__state { get; set; }
public string zip { get; set; }
public Period period { get; set; }
}
public class PerioD2
{
public string start { get; set; }
public string end { get; set; }
}
public class Name
{
public string use { get; set; }
public List<string> family { get; set; }
public List<string> given { get; set; }
public PerioD2 __invalid_name__perio
d { get; set; }
}
public class Gender
{
public string __invalid_name__co
de { get; set; }
public string display { get; set; }
}
public class Period3
{
public string start { get; set; }
public string __invalid_name__end { get; set; }
}
public class Identifier
{
public string use
{ get; set; }
public string system { get; set; }
public string key { get; set; }
public Period3 period { get; set; }
}
public class Period4
{
public string start { get; set; }
public string end { get; set; }
}
public class Telecom
{
public string system { get; set; }
public string value { get; set; }
public string use { get; set; }
public Period4 period { get; set; }
}
public class Content
{
public string contentType { get; set; }
public string language { get; set; }
public string __invalid_name__dat
a { get; set; }
public int size { get; set; }
public string hash { get; set; }
public string title { get; set; }
}
public class Photo
{
public Content content { get; set; }
}
public class Details
{
public List<Address> address { get; set; }
public List<Name> name { get; set; }
public Gender gender { get; set; }
public string birthDate { get; set; }
public List<Identifier> identifier { get; set; }
public List<Telecom> telecom { get; set; }
public List<Photo> photo { get; set; }
}
public class EnrollmentSummary
{
public string dateEnrolled { get; set; }
public string __invalid_name__en
roller { get; set; }
}
public class Self2
{
public string href { get; set; }
}
public class UnEnroll
{
public string href { get; set; }
}
public class PersonLink
{
public string href { get; set; }
}
public class PersonMatch
{
public string href { get; set; }
}
public class Links2
{
public Self2 self { get; set; }
public UnEnroll __invalid_name__un
enroll { get; set; }
public PersonLink personLink { get; set; }
public PersonMatch personMatch { get; set; }
}
public class Person
{
public Details details { get; set; }
public bool __invalid_name__e
nrolled { get; set; }
public EnrollmentSummary enrollmentSummary { get; set; }
public Links2 _links { get; set; }
}
public class Embedded
{
public List<Person> person { get; set; }
}
public class RootObject
{
public SearchParameters searchParameters { get; set; }
public string message { get; set; }
public LinKs __invalid_name___lin
ks { get; set; }
public Embedded _embedded { get; set; }
}
The following function will convert JSON into a C# class where T is the class type.
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms); //
return obj;
}
}
You need a reference to the System.Runtime.Serialization.json namespace.
The function is called in the following manner;
calendarList = Deserialise<GoogleCalendarList>(calendarListString);
calendarlist being the C# class and calendarListString the string containing the JSON.

InvalidOperationException when Serializing

I get an InvalidOperationException when trying to reflect the "listing" property, as said by inner exception. When it tries to serialize ArmyListing.
All the variables are public.
Checked List can be serialized. Most errors I found where with people using Dictionaries which can't.
Any idea why it appears not to be serializable?
//[Serializable]
public class ArmyListing
{
[XmlElement("army")]
public List<Army> listing { get; set; }
public void SerializeToXML(ArmyListing armyListing)
{
try
{
XmlSerializer serializer = new XmlSerializer(typeof(ArmyListing));
TextWriter textWriter = new StreamWriter(#"C:\Test\40k.xml");
serializer.Serialize(textWriter, armyListing);
textWriter.Close();
}
catch (Exception ex) { }
}
}
//[Serializable]
public class Army
{
//public Army();
[XmlAttribute]
[XmlArray("unit-category")]
public List<UnitCategory> settingconstraints { get; set; }
[XmlAttribute("name")]
public string armyName { get; set; }
}
//[Serializable]
public class UnitCategory
{
//public UnitCategory();
[XmlArray("unit-type")]
public List<UnitType> setting { get; set; }
[XmlAttribute("name")]
public string unitCategoryName { get; set; }
}
//[Serializable]
public class UnitType
{
//public UnitType();
[XmlArray("unit")]
public List<Unit> setting { get; set; }
[XmlAttribute("name")]
public string unitTypeName { get; set; }
}
//[Serializable]
public class Unit
{
//public Unit();
[XmlAttribute("name")]
public string unitName { get; set; }
[XmlAttribute("composition")]
public string compsition { get; set; }
[XmlAttribute("weapon-skill")]
public string weaponSkill { get; set; }
[XmlAttribute("ballistic-skill")]
public string ballisticSkill { get; set; }
[XmlAttribute("strength")]
public string strength { get; set; }
[XmlAttribute("toughness")]
public string T { get; set; }
[XmlAttribute("wounds")]
public string wounds { get; set; }
[XmlAttribute("initiative")]
public string initiative { get; set; }
[XmlAttribute("attacks")]
public string attacks { get; set; }
[XmlAttribute("leadership")]
public string leadership { get; set; }
[XmlAttribute("saving-throw")]
public string saveThrow { get; set; }
[XmlAttribute("armour")]
public string armour { get; set; }
[XmlAttribute("weapons")]
public string weapons { get; set; }
[XmlAttribute("special-rules")]
public string specialRules { get; set; }
[XmlAttribute("dedicated-transport")]
public string dedicatedTransport { get; set; }
[XmlAttribute("options")]
public string options { get; set; }
}
//Form
namespace ThereIsOnlyRules
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
ArmyListing armyListing = new ArmyListing();
armyListing.SerializeToXML(armyListing);
}
}
}
This is the part that doesn't work:
[XmlAttribute]
[XmlArray("unit-category")]
[XmlArray] & [XmlAttribute] can't both be defined on the same property.
If you keep drilling into .InnerException until you get to the original problem, the serializer even tells you this:
There was an error reflecting type 'ArmyListing'.
There was an error reflecting property 'listing'.
There was an error reflecting type 'Army'.
There was an error reflecting property 'settingconstraints'.
XmlAttribute and XmlAnyAttribute cannot be used in conjunction with XmlElement, XmlText, XmlAnyElement, XmlArray, or XmlArrayItem.

Categories