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.
Related
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
I am using the SharePoint REST API to do a search. I am pulling back the JSON results and reading them as follows:
HttpWebRequest endpointRequest = (HttpWebRequest)HttpWebRequest.Create(querystring);
endpointRequest.Method = "GET";
endpointRequest.Accept = "application/json; odata=verbose";
endpointRequest.UseDefaultCredentials = true;
HttpWebResponse endpointResponse =(HttpWebResponse)endpointRequest.GetResponse();
Stream webStream = endpointResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
var results = responseReader.ReadToEnd();
This works fine, I can see the results in JSON format. So I created a class from the JSON in VS 2017 and here is the classes created from the JSON (this was done automatically with File=>Paste Special=>Paste JSON As Classes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class SharePointRESTResults
{
public class Rootobject
{
public D d { get; set; }
}
public class D
{
public Query query { get; set; }
}
public class Query
{
public __Metadata __metadata { get; set; }
public int ElapsedTime { get; set; }
public Primaryqueryresult PrimaryQueryResult { get; set; }
public Properties1 Properties { get; set; }
public Secondaryqueryresults SecondaryQueryResults { get; set; }
public string SpellingSuggestion { get; set; }
public Triggeredrules TriggeredRules { get; set; }
}
public class __Metadata
{
public string type { get; set; }
}
public class Primaryqueryresult
{
public __Metadata1 __metadata { get; set; }
public Customresults CustomResults { get; set; }
public string QueryId { get; set; }
public string QueryRuleId { get; set; }
public object RefinementResults { get; set; }
public Relevantresults RelevantResults { get; set; }
public object SpecialTermResults { get; set; }
}
public class __Metadata1
{
public string type { get; set; }
}
public class Customresults
{
public __Metadata2 __metadata { get; set; }
public object[] results { get; set; }
}
public class __Metadata2
{
public string type { get; set; }
}
public class Relevantresults
{
public __Metadata3 __metadata { get; set; }
public object GroupTemplateId { get; set; }
public object ItemTemplateId { get; set; }
public Properties Properties { get; set; }
public object ResultTitle { get; set; }
public object ResultTitleUrl { get; set; }
public int RowCount { get; set; }
public Table Table { get; set; }
public int TotalRows { get; set; }
public int TotalRowsIncludingDuplicates { get; set; }
}
public class __Metadata3
{
public string type { get; set; }
}
public class Properties
{
public Result[] results { get; set; }
}
public class Result
{
public __Metadata4 __metadata { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
public class __Metadata4
{
public string type { get; set; }
}
public class Table
{
public __Metadata5 __metadata { get; set; }
public Rows Rows { get; set; }
}
public class __Metadata5
{
public string type { get; set; }
}
public class Rows
{
public Result1[] results { get; set; }
}
public class Result1
{
public __Metadata6 __metadata { get; set; }
public Cells Cells { get; set; }
}
public class __Metadata6
{
public string type { get; set; }
}
public class Cells
{
public Result2[] results { get; set; }
}
public class Result2
{
public __Metadata7 __metadata { get; set; }
public string Key { get; set; }
public object Value { get; set; }
public string ValueType { get; set; }
}
public class __Metadata7
{
public string type { get; set; }
}
public class Properties1
{
public Result3[] results { get; set; }
}
public class Result3
{
public __Metadata8 __metadata { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public string ValueType { get; set; }
}
public class __Metadata8
{
public string type { get; set; }
}
public class Secondaryqueryresults
{
public __Metadata9 __metadata { get; set; }
public object[] results { get; set; }
}
public class __Metadata9
{
public string type { get; set; }
}
public class Triggeredrules
{
public __Metadata10 __metadata { get; set; }
public object[] results { get; set; }
}
public class __Metadata10
{
public string type { get; set; }
}
}
}
So I now am trying to deserialize the results as follows:
SharePointRESTResults resultX = JsonConvert.DeserializeObject<SharePointRESTResults>(results());
The results I need should be in the Result2 Class. The problem I have is that this line is setting resultX = to "ConsoleApplication1.SharePointRESTResults" and nothing more. I looked in the JSON Serializing and Deserializing here: JSON Documentation but still cannot get the results into the class so I can pull out the data. I appreciate any help.
The main points are -
The Account Declaration.
JsonProperty attribute.
NOTE : If you have an object Which keys can change, Then you need to use a
Dictionary<string, T>
. A regular class won't work for that; neither will a
List<T>
.
I want to create a class that have a class but this second class may be different each time the first class is called. For example:
public class ServerResponseObject
{
public string statusCode { get; set; }
public string errorCode { get; set; }
public string errorDescription { get; set; }
public Object obj { get; set; }
public ServerResponseObject(Object obje)
{
obj = obje;
}
}
public class TVChannelObject
{
public string number { get; set; }
public string title { get; set; }
public string FavoriteChannel { get; set; }
public string description { get; set; }
public string packageid { get; set; }
public string format { get; set; }
}
public class ChannelCategoryObject
{
public string id { get; set; }
public string name { get; set; }
}
How can I do it to call the ServerResponseObject with different objects each time, once with TVChannelObject and once with ChannelCategoryObject?
What you're looking for is a generic type parameter:
public class ServerResponseObject<T>
{
public ServerResponseObject(T obj)
{
Obj = obj;
}
public T Obj { get; set; }
}
I have this model:
[XmlArray(ElementName = "Listing")]
[XmlArrayItem(ElementName = "Classification")]
public List<Classification> classifications { get; set; }
[XmlRoot("Listing")]
public class Classification
{
[XmlAttribute("Name")]
public string name { get; set; }
[XmlText]
public string Value { get; set; }
}
That gives me this:
<Listing>
<Classification Name="Location">AsiaPacific</Classification>
</Listing>
How should I modify my class to get this:
<Listing reference = "MyReference">
<Classification Name="Location">AsiaPacific</Classification>
</Listing>
After a few (hundreds) trial and error, I got the result that I need by modifying the model to:
[XmlElement(ElementName = "Listing")]
public ClassificationWrapper classificationWrapper { get; set; }
public class ClassificationWrapper
{
[XmlAttribute("reference")]
public string ref= "MyReference";
[XmlElement("Classification", typeof(Classification))]
public List<Classification> classifications { get; set; }
public ClassificationWrapper() { this.classifications = new List<Classification>(); }
}
public class Classification
{
[XmlAttribute("Name")]
public string name { get; set; }
[XmlText]
public string Value { get; set; }
}
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.