Deserialize with Json.Net fails on some fields - c#

I try to deserialze Json into a c# object using Json.Net.
c# class:
public class Evaluation
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "avg")]
public string Average { get; set; }
[DataMember(Name = "median")]
public string Median { get; set; }
[DataMember(Name = "teacherID")]
public int TeacherId { get; set; }
[DataMember(Name = "evalType")]
public int EvaluationType { get; set; }
}
Unit Test:
[Test]
[TestCase()]
public void TestParsing()
{
string json = "{" +
"\"id\": 439476," +
"\"avg\": \"69\"," +
"\"median\": \"75\"," +
"\"teacherID\": 1," +
"\"evalType\": 1" +
"}";
Evaluation evaluation = JsonConvert.DeserializeObject<Evaluation>(json);
Assert.IsTrue(evaluation.Average.Equals("69"));
Assert.IsTrue(evaluation.EvaluationType == 1);
}
This fails because evaluation.Average is null and evaluation.EvaluationType is 0. The other fields are parsed correctly.
Why is this failing?

Setting the DataContract attribute on your class declaration should fix the problem:
[DataContract]
public class Evaluation
{
[DataMember(Name = "id")]
public int Id { get; set; }
[DataMember(Name = "avg")]
public string Average { get; set; }
[DataMember(Name = "median")]
public string Median { get; set; }
[DataMember(Name = "teacherID")]
public int TeacherId { get; set; }
[DataMember(Name = "evalType")]
public int EvaluationType { get; set; }
}

Related

Parse response of Form Data in C#

type=CREATE
resource=transaction
number_of_attempts=1
data={"id":"11e7df5131dd9820bf774044","payment_method":"cc","account_vault_id":null,"recurring_id":null,"first_six":"411111","last_four":"1111","account_holder_name":" MALCOLM BLACK","transaction_amount":"1.00","description":null,"transaction_code":null,"avs":null,"batch":"2","order_num":"798279608211","verbiage":"APPROVAL","transaction_settlement_status":null,"effective_date":null,"routing":null,"return_date":null,"created_ts":1513092547,"modified_ts":1513092547,"transaction_api_id":null,"terms_agree":null,"notification_email_address":null,"notification_email_sent":true,"response_message":null,"auth_amount":"1.00","auth_code":"df5132","status_id":101,"type_id":20,"location_id":"11e7c499daaff1f0a7507909","reason_code_id":1000,"contact_id":"11e7c619b69d209ab41b24dc","billing_zip":"","billing_street":null,"product_transaction_id":"11e7c499db893b0489bb3739","tax":"0.000","customer_ip":null,"customer_id":null,"po_number":null,"avs_enhanced":"V","cvv_response":"N","billing_phone":null,"billing_city":null,"billing_state":null,"clerk_number":null,"tip_amount":"0.00","created_user_id":"11e7c499dac79026a4e740f1","modified_user_id":"11e7c499dac79026a4e740f1","settle_date":null,"charge_back_date":null,"void_date":null,"account_type":"visa","is_recurring":false,"is_accountvault":false,"transaction_c1":null,"transaction_c2":null,"transaction_c3":null,"additional_amounts":[],"terminal_serial_number":null,"entry_mode_id":"K","terminal_id":null,"quick_invoice_id":null,"emv_receipt_data":null}
This is the Form data i am receiving in C# using
string data=Request.Form("data");
Now data is nested how can i get the values of data object. Parsing it in json using JsonConvert.Deserialize is throwing exception.
The original response is:
type=CREATE&resource=transaction&number_of_attempts=1&data=%7b%22id%22%3a%2211e7df5131dd9820bf774044%22%2c%22payment_method%22%3a%22cc%22%2c%22account_vault_id%22%3anull%2c%22recurring_id%22%3anull%2c%22first_six%22%3a%22411111%22%2c%22last_four%22%3a%221111%22%2c%22account_holder_name%22%3a%22+MALCOLM+BLACK%22%2c%22transaction_amount%22%3a%221.00%22%2c%22description%22%3anull%2c%22transaction_code%22%3anull%2c%22avs%22%3anull%2c%22batch%22%3a%222%22%2c%22order_num%22%3a%22798279608211%22%2c%22verbiage%22%3a%22APPROVAL%22%2c%22transaction_settlement_status%22%3anull%2c%22effective_date%22%3anull%2c%22routing%22%3anull%2c%22return_date%22%3anull%2c%22created_ts%22%3a1513092547%2c%22modified_ts%22%3a1513092547%2c%22transaction_api_id%22%3anull%2c%22terms_agree%22%3anull%2c%22notification_email_address%22%3anull%2c%22notification_email_sent%22%3atrue%2c%22response_message%22%3anull%2c%22auth_amount%22%3a%221.00%22%2c%22auth_code%22%3a%22df5132%22%2c%22status_id%22%3a101%2c%22type_id%22%3a20%2c%22location_id%22%3a%2211e7c499daaff1f0a7507909%22%2c%22reason_code_id%22%3a1000%2c%22contact_id%22%3a%2211e7c619b69d209ab41b24dc%22%2c%22billing_zip%22%3a%22%22%2c%22billing_street%22%3anull%2c%22product_transaction_id%22%3a%2211e7c499db893b0489bb3739%22%2c%22tax%22%3a%220.000%22%2c%22customer_ip%22%3anull%2c%22customer_id%22%3anull%2c%22po_number%22%3anull%2c%22avs_enhanced%22%3a%22V%22%2c%22cvv_response%22%3a%22N%22%2c%22billing_phone%22%3anull%2c%22billing_city%22%3anull%2c%22billing_state%22%3anull%2c%22clerk_number%22%3anull%2c%22tip_amount%22%3a%220.00%22%2c%22created_user_id%22%3a%2211e7c499dac79026a4e740f1%22%2c%22modified_user_id%22%3a%2211e7c499dac79026a4e740f1%22%2c%22settle_date%22%3anull%2c%22charge_back_date%22%3anull%2c%22void_date%22%3anull%2c%22account_type%22%3a%22visa%22%2c%22is_recurring%22%3afalse%2c%22is_accountvault%22%3afalse%2c%22transaction_c1%22%3anull%2c%22transaction_c2%22%3anull%2c%22transaction_c3%22%3anull%2c%22additional_amounts%22%3a%5b%5d%2c%22terminal_serial_number%22%3anull%2c%22entry_mode_id%22%3a%22K%22%2c%22terminal_id%22%3anull%2c%22quick_invoice_id%22%3anull%2c%22emv_receipt_data%22%3anull%7d
UPDATE:
try
{
string data = #Request.Form.Get("data");
//now data=
//{"id":"11e7df5131dd9820bf774044","payment_method":"cc","account_vault_id":n//ull.....}
//data = '"' + data + '"';
var stringfy = JsonConvert.DeserializeObject(data);
File.WriteAllText(path, " File Data : " + Request.Form +
Environment.NewLine + " --------------------Total Value 0 " + Request.Form.Keys[0].ToString()
+ Environment.NewLine + " --------------------Total Value 1 " + Request.Form.Keys[1].ToString()
+ Environment.NewLine + " --------------------Total Value 2 " + Request.Form.Keys[2].ToString()
+ Environment.NewLine + " --------------------Total Value 3 " + data);
}
catch (Exception ex)
{
File.WriteAllText(path, "Exception :1 "+ex.Message.ToString());
}
Code is deployed on server so writing exceptions to file but, no code after Deserialize statement is working and no file is being created.
There is a shortcut. You can use this website as a helper - http://json2csharp.com/
All you need to do is past this string {"id":"11e7d...} then click generate.
// To parse this JSON data, add NuGet 'Newtonsoft.Json' then do:
//
// using QuickType;
//
// var data = Welcome.FromJson(jsonString);
//
namespace QuickType
{
using System;
using System.Net;
using System.Collections.Generic;
using Newtonsoft.Json;
public partial class Welcome
{
[JsonProperty("account_holder_name")]
public string AccountHolderName { get; set; }
[JsonProperty("account_type")]
public string AccountType { get; set; }
[JsonProperty("account_vault_id")]
public object AccountVaultId { get; set; }
[JsonProperty("additional_amounts")]
public object[] AdditionalAmounts { get; set; }
[JsonProperty("auth_amount")]
public string AuthAmount { get; set; }
[JsonProperty("auth_code")]
public string AuthCode { get; set; }
[JsonProperty("avs")]
public object Avs { get; set; }
[JsonProperty("avs_enhanced")]
public string AvsEnhanced { get; set; }
[JsonProperty("batch")]
public string Batch { get; set; }
[JsonProperty("billing_city")]
public object BillingCity { get; set; }
[JsonProperty("billing_phone")]
public object BillingPhone { get; set; }
[JsonProperty("billing_state")]
public object BillingState { get; set; }
[JsonProperty("billing_street")]
public object BillingStreet { get; set; }
[JsonProperty("billing_zip")]
public string BillingZip { get; set; }
[JsonProperty("charge_back_date")]
public object ChargeBackDate { get; set; }
[JsonProperty("clerk_number")]
public object ClerkNumber { get; set; }
[JsonProperty("contact_id")]
public string ContactId { get; set; }
[JsonProperty("created_ts")]
public long CreatedTs { get; set; }
[JsonProperty("created_user_id")]
public string CreatedUserId { get; set; }
[JsonProperty("customer_id")]
public object CustomerId { get; set; }
[JsonProperty("customer_ip")]
public object CustomerIp { get; set; }
[JsonProperty("cvv_response")]
public string CvvResponse { get; set; }
[JsonProperty("description")]
public object Description { get; set; }
[JsonProperty("effective_date")]
public object EffectiveDate { get; set; }
[JsonProperty("emv_receipt_data")]
public object EmvReceiptData { get; set; }
[JsonProperty("entry_mode_id")]
public string EntryModeId { get; set; }
[JsonProperty("first_six")]
public string FirstSix { get; set; }
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("is_accountvault")]
public bool IsAccountvault { get; set; }
[JsonProperty("is_recurring")]
public bool IsRecurring { get; set; }
[JsonProperty("last_four")]
public string LastFour { get; set; }
[JsonProperty("location_id")]
public string LocationId { get; set; }
[JsonProperty("modified_ts")]
public long ModifiedTs { get; set; }
[JsonProperty("modified_user_id")]
public string ModifiedUserId { get; set; }
[JsonProperty("notification_email_address")]
public object NotificationEmailAddress { get; set; }
[JsonProperty("notification_email_sent")]
public bool NotificationEmailSent { get; set; }
[JsonProperty("order_num")]
public string OrderNum { get; set; }
[JsonProperty("payment_method")]
public string PaymentMethod { get; set; }
[JsonProperty("po_number")]
public object PoNumber { get; set; }
[JsonProperty("product_transaction_id")]
public string ProductTransactionId { get; set; }
[JsonProperty("quick_invoice_id")]
public object QuickInvoiceId { get; set; }
[JsonProperty("reason_code_id")]
public long ReasonCodeId { get; set; }
[JsonProperty("recurring_id")]
public object RecurringId { get; set; }
[JsonProperty("response_message")]
public object ResponseMessage { get; set; }
[JsonProperty("return_date")]
public object ReturnDate { get; set; }
[JsonProperty("routing")]
public object Routing { get; set; }
[JsonProperty("settle_date")]
public object SettleDate { get; set; }
[JsonProperty("status_id")]
public long StatusId { get; set; }
[JsonProperty("tax")]
public string Tax { get; set; }
[JsonProperty("terminal_id")]
public object TerminalId { get; set; }
[JsonProperty("terminal_serial_number")]
public object TerminalSerialNumber { get; set; }
[JsonProperty("terms_agree")]
public object TermsAgree { get; set; }
[JsonProperty("tip_amount")]
public string TipAmount { get; set; }
[JsonProperty("transaction_amount")]
public string TransactionAmount { get; set; }
[JsonProperty("transaction_api_id")]
public object TransactionApiId { get; set; }
[JsonProperty("transaction_c1")]
public object TransactionC1 { get; set; }
[JsonProperty("transaction_c2")]
public object TransactionC2 { get; set; }
[JsonProperty("transaction_c3")]
public object TransactionC3 { get; set; }
[JsonProperty("transaction_code")]
public object TransactionCode { get; set; }
[JsonProperty("transaction_settlement_status")]
public object TransactionSettlementStatus { get; set; }
[JsonProperty("type_id")]
public long TypeId { get; set; }
[JsonProperty("verbiage")]
public string Verbiage { get; set; }
[JsonProperty("void_date")]
public object VoidDate { get; set; }
}
public partial class Welcome
{
public static Welcome FromJson(string json) => JsonConvert.DeserializeObject<Welcome>(json, Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this Welcome self) => JsonConvert.SerializeObject(self, Converter.Settings);
}
public class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
};
}
}

Deserializing JSON objects, keep getting errors (C#)

I am trying to deserialize my json code. The json code is in a string, and the json code looks like this (so I'm assuming it's json objects)
{
"post_id":13,
"thread_id":9,
"user_id":1,
"username":"Username",
"post_date":1496439611,
"message":"testzilla - 2133746943A9",
"ip_id":698,
"message_state":"visible",
"attach_count":0,
"position":0,
"likes":0,
"like_users":"a:0:{}",
"warning_id":0,
"warning_message":"",
"last_edit_date":1496476199,
"last_edit_user_id":0,
"edit_count":9,
"node_id":34,
"title":"Test",
"tags":"a:0:{}",
"node_title":"test node",
"node_name":null,
"message_html":"testzilla - 2133746943A9",
"absolute_url":"url"
}
How would I put the "message" container inside a string? So that the string would contain "testzilla - 2133746943A9" without the quotation marks. I am using JSON.Net
The name of the string that contains this json code is "MACs". Thanks in advance. PS: I am a new coder.
there is a missing "{" at the beginning of your json file, try adding it
You need to create your c# class to deserialize your json string. As per your json structure i have created your class given below
public class MyClass
{
public int post_id { get; set; }
public int thread_id { get; set; }
public int user_id { get; set; }
public string username { get; set; }
public int post_date { get; set; }
public string message { get; set; }
public int ip_id { get; set; }
public string message_state { get; set; }
public int attach_count { get; set; }
public int position { get; set; }
public int likes { get; set; }
public string like_users { get; set; }
public int warning_id { get; set; }
public string warning_message { get; set; }
public int last_edit_date { get; set; }
public int last_edit_user_id { get; set; }
public int edit_count { get; set; }
public int node_id { get; set; }
public string title { get; set; }
public string tags { get; set; }
public string node_title { get; set; }
public object node_name { get; set; }
public string message_html { get; set; }
public string absolute_url { get; set; }
}
No need to use library JSON.Net. You can do this by simply using System.Web.Script.Serialization to deserialize the json string.
Note : System.Web.Script.Serialization is available inside System.Web.Extensions namespace.
Below is the complete code. I kept your json data inside a file named as "test2.json" and consuming it from that file.
using System;
using System.Web.Script.Serialization;
using System.IO;
namespace DesrializeJson1ConsoleApp
{
class Program
{
static void Main(string[] args)
{
var jsonFile = "test2.json";
string jsonstring = File.ReadAllText(jsonFile);
var serializer = new JavaScriptSerializer();
MyClass aClass = serializer.Deserialize<MyClass>(jsonstring);
Console.WriteLine("--------------------------");
Console.WriteLine("message :" + aClass.message);
Console.WriteLine("message_state :" + aClass.message_state);
Console.WriteLine("warning_message :" + aClass.warning_message);
Console.WriteLine("message_html :" + aClass.message_html);
Console.WriteLine("--------------------------");
Console.Read();
}
}
public class MyClass
{
public int post_id { get; set; }
public int thread_id { get; set; }
public int user_id { get; set; }
public string username { get; set; }
public int post_date { get; set; }
public string message { get; set; }
public int ip_id { get; set; }
public string message_state { get; set; }
public int attach_count { get; set; }
public int position { get; set; }
public int likes { get; set; }
public string like_users { get; set; }
public int warning_id { get; set; }
public string warning_message { get; set; }
public int last_edit_date { get; set; }
public int last_edit_user_id { get; set; }
public int edit_count { get; set; }
public int node_id { get; set; }
public string title { get; set; }
public string tags { get; set; }
public string node_title { get; set; }
public object node_name { get; set; }
public string message_html { get; set; }
public string absolute_url { get; set; }
}
}
OUTPUT
You can use regex to get the value you want.
string yourJsonString = #"{ ""post_id"":13, ""thread_id"":9, ""user_id"":1, ""username"":""Username"", ""post_date"":1496439611, ""message"":""testzilla - 2133746943A9"", ""ip_id"":698, ""message_state"":""visible"", ""attach_count"":0, ""position"":0, ""likes"":0, ""like_users"":""a:0:{}"", ""warning_id"":0, ""warning_message"":"""", ""last_edit_date"":1496476199, ""last_edit_user_id"":0, ""edit_count"":9, ""node_id"":34, ""title"":""Test"", ""tags"":""a:0:{}"", ""node_title"":""test node"", ""node_name"":null, ""message_html"":""testzilla - 2133746943A9"", ""absolute_url"":""url""}";
string value = System.Text.RegularExpressions.Regex.Match(yourJsonString,#"""message"":(.+?),").Groups[1].Value.Replace(#"""","");
MessageBox.Show(value);
You can also use dynamic type for deserialization. You will no need to write object for deserialization:
var str = "{\r\n \"post_id\":13,\r\n \"thread_id\":9,\r\n \"user_id\":1,\r\n \"username\":\"Username\",\r\n \"post_date\":1496439611,\r\n \"message\":\"testzilla - 2133746943A9\",\r\n \"ip_id\":698,\r\n \"message_state\":\"visible\",\r\n \"attach_count\":0,\r\n \"position\":0,\r\n \"likes\":0,\r\n \"like_users\":\"a:0:{}\",\r\n \"warning_id\":0,\r\n \"warning_message\":\"\",\r\n \"last_edit_date\":1496476199,\r\n \"last_edit_user_id\":0,\r\n \"edit_count\":9,\r\n \"node_id\":34,\r\n \"title\":\"Test\",\r\n \"tags\":\"a:0:{}\",\r\n \"node_title\":\"test node\",\r\n \"node_name\":null,\r\n \"message_html\":\"testzilla - 2133746943A9\",\r\n \"absolute_url\":\"url\"\r\n}";
dynamic obj = JsonConvert.DeserializeObject(str);
var postId = obj.post_id;
Console.WriteLine("postId:" + postId);
output:
postId:13

how to collect dataset in dataobject?

I want to collect the information of this Json:
{"name":"Maltarya","race":"Sylvari","gender":"Female","profession":"Thief","level":80,"equipment":[{"id":4483,"slot":"HelmAquatic","upgrades":[24723]},{"id":59,"slot":"Backpack","upgrades":[24498],"skin":2381},{"id":11805,"slot":"Coat","upgrades":[24815]},{"id":11889,"slot":"Boots","upgrades":[24723]},{"id":11847,"slot":"Gloves","upgrades":[24815]},{"id":11973,"slot":"Helm","upgrades":[24815]},{"id":11763,"slot":"Leggings","upgrades":[24815]},{"id":11931,"slot":"Shoulders","upgrades":[24815]},{"id":39141,"slot":"Accessory1","upgrades":[24545]}]}
But i have an error when i want to collect the equipment informations.
My code is:
WebRequest request = WebRequest.Create("https://api.guildwars2.com/v2/characters/" + name + "?access_token=" + key);
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Personnages perso = JsonConvert.DeserializeObject<Personnages>(responseString);
and my Personnages class:
class Personnages
{
public string name { get; set; }
public string race { get; set; }
public string gender { get; set; }
public string profession { get; set; }
public string level { get; set; }
public IList<string> equipment { get; set; }
}
The exception i have is: Unexpected token: Error reading string. StartObject.
You are trying to deserialize JSON array to a IList<string>. However, this array contains objects, but not strings.
You need to implement another one class for these objects and use it in deserialization:
class EquipmentItem
{
public int id { get; set; }
public string slot { get; set; }
public List<int> upgrades { get; set; }
}
class Personnages
{
public string name { get; set; }
public string race { get; set; }
public string gender { get; set; }
public string profession { get; set; }
public string level { get; set; }
public List<EquipmentItem> equipment { get; set; }
}
Personnages perso = JsonConvert.DeserializeObject<Personnages>(responseString);

Deserialize xml xmpp message to object

I'm trying to deserialize a xml string to a c# object. This is the message:
<message from='test1#localhost' to='test2#localhost'><result xmlns='urn:xmpp:mam:tmp' id='A6QV1I4TKO81'><forwarded xmlns='urn:xmpp:forward:0'><delay xmlns='urn:xmpp:delay' from='test1#localhost' stamp='2015-07-21T09:12:09Z'></delay><message type='mchat'><subject/><body/></message></forwarded></result></message>
And this is the class
public class Delay {
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
[XmlAttribute(AttributeName="from")]
public string From { get; set; }
[XmlAttribute(AttributeName="stamp")]
public string Stamp { get; set; }
}
public class Active {
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
}
public class XmppMessage {
[XmlElement(ElementName="body")]
public string Body { get; set; }
[XmlAttribute(AttributeName="lang")]
public string Lang { get; set; }
[XmlAttribute(AttributeName="type")]
public string Type { get; set; }
[XmlAttribute(AttributeName="id")]
public string Id { get; set; }
[XmlAttribute(AttributeName="to")]
public string To { get; set; }
}
public class Forwarded {
[XmlElement(ElementName="delay")]
public Delay Delay { get; set; }
[XmlElement(ElementName="message")]
public XmppMessage Message { get; set; }
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
}
public class Result {
[XmlElement(ElementName="forwarded")]
public Forwarded Forwarded { get; set; }
[XmlAttribute(AttributeName="xmlns")]
public string Xmlns { get; set; }
[XmlAttribute(AttributeName="id")]
public string Id { get; set; }
}
[XmlRoot(ElementName="message")]
public class MessageHistory {
[XmlElement(ElementName="result")]
public Result Result { get; set; }
[XmlAttribute(AttributeName="from")]
public string From { get; set; }
[XmlAttribute(AttributeName="to")]
public string To { get; set; }
}
This is the code to deserialise:
MessageHistory messageNode;
XmlSerializer serializer = new XmlSerializer(typeof(MessageHistory));
using (StringReader reader = new StringReader(message))
{
messageNode = (MessageHistory)(serializer.Deserialize(reader));
}
The object property "from" and "to" are fine but the "Result" is returning null. I can't understand what I'm missing here...
The problem is the namespaces in the XML. you have to specify the namespaces explicitly, like this:
public class Forwarded
{
[XmlElement(ElementName = "delay", Namespace = "urn:xmpp:delay")]
public Delay Delay { get; set; }
[XmlElement(ElementName = "message")]
public XmppMessage Message { get; set; }
[XmlAttribute(AttributeName = "xmlns")]
public string Xmlns { get; set; }
}
public class Result
{
[XmlElement(ElementName = "forwarded", Namespace = "urn:xmpp:forward:0")]
public Forwarded Forwarded { get; set; }
[XmlAttribute(AttributeName = "xmlns")]
public string Xmlns { get; set; }
[XmlAttribute(AttributeName = "id")]
public string Id { get; set; }
}
[XmlRoot(ElementName = "message")]
public class MessageHistory
{
[XmlElement(ElementName = "result", Namespace = "urn:xmpp:mam:tmp")]
public Result Result { get; set; }
[XmlAttribute(AttributeName = "from")]
public string From { get; set; }
[XmlAttribute(AttributeName = "to")]
public string To { get; set; }
}

InvalidOperationException Error Reflecting Class

After read multiples posts related on this error and not found an solution to my problem, I explain it here.
I use XmlSerializer to serialize simple classes.
Here's my code:
private void btnGenerateXml_Click(object sender, RoutedEventArgs e)
{
Orchard orchard = new Orchard
{
Recipe = new Recipe
{
Name = "Generated by JooWeb.Tools",
Author = "admin",
ExportUtc = DateTime.UtcNow
},
MyDatas = new MyDatas
{
//Test = "test"
TrendDatas = new TrendDatas
{
Id = null,
Status = "Published",
TrendDatasPart = new TrendDatasPart
{
IdSource = 0,
PostalCode = "1000",
Locality = "Test5",
Surface = (decimal)0.00,
Price = (decimal)0.00,
Type = "",
InsertDateIndicator = "",
UpdateDateIndicator = "",
GetFromDate = DateTime.Now,
UpdatedDate = new DateTime(1900, 1, 1)
},
CommonPart = new CommonPart
{
Owner = "/User.UserName=admin",
CreatedUtc = DateTime.UtcNow,
PublishedUtc = DateTime.UtcNow,
ModifiedUtc = DateTime.UtcNow
}
}
}
};
XmlSerializer orchardXmlSerializer = new XmlSerializer(typeof(Orchard));
var path = #"C:\Temp\orchardFileImport_" + string.Format("{0:yyyyMMdd}", DateTime.Today) + ".xml";
if (File.Exists(path))
File.Delete(path);
orchardXmlSerializer.Serialize(File.OpenWrite(path), orchard);
MessageBox.Show("Finished");
}
}
[XmlRoot]
public class Orchard
{
[XmlElement]
public Recipe Recipe { get; set; }
[XmlElement(ElementName = "Data")]
public MyDatas MyDatas { get; set; }
}
public class Recipe
{
[XmlElement]
public string Name { get; set; }
[XmlElement]
public string Author { get; set; }
[XmlElement]
public DateTime ExportUtc { get; set; }
}
public class MyDatas
{
public MyDatas()
{
}
//[XmlElement]
//public string Test { get; set; }
[XmlElement]
public TrendDatas TrendDatas { get; set; }
}
public class TrendDatas
{
[XmlAttribute]
public string Status { get; set; }
[XmlAttribute]
public int? Id { get; set; }
//[XmlIgnore]
[XmlElement]
public TrendDatasPart TrendDatasPart { get; set; }
//[XmlIgnore]
[XmlElement]
public CommonPart CommonPart { get; set; }
}
public class TrendDatasPart
{
[XmlAttribute]
public int IdSource { get; set; }
[XmlAttribute]
public string PostalCode { get; set; }
[XmlAttribute]
public string Locality { get; set; }
[XmlAttribute]
public decimal Surface { get; set; }
[XmlAttribute]
public decimal Price { get; set; }
[XmlAttribute]
public string Type { get; set; }
[XmlAttribute]
public string InsertDateIndicator { get; set; }
[XmlAttribute]
public string UpdateDateIndicator { get; set; }
[XmlAttribute]
public DateTime GetFromDate { get; set; }
[XmlAttribute]
public DateTime UpdatedDate { get; set; }
}
public class CommonPart
{
[XmlAttribute]
public string Owner { get; set; }
[XmlAttribute]
public DateTime CreatedUtc { get; set; }
[XmlAttribute]
public DateTime PublishedUtc { get; set; }
[XmlAttribute]
public DateTime ModifiedUtc { get; set; }
}
With this code when I click on Generate xml file, I got the error InvalidOperationException
There was an error reflecting type 'MergeExcelFiles.Orchard'.
{"There was an error reflecting property 'MyDatas'."}
Like you see in my comments, I try to just add a string xmlElement to node MyDatas, with this change I got no error but in the xml file I don't have any node with name Data.
I don't understand why with class Recipe all look right but with node MyDatas nothing showed in xml file or got this error "InvalidOperationException".
You need to dig into your error message more because the reason is in the innermost exception:
System.InvalidOperationException: Cannot serialize member 'Id' of type System.Nullable`1[System.Int32]. XmlAttribute/XmlText cannot be used to encode complex types.
The issue is that you have a nullable value type as a property (TrendDatas.Id) to be serialized as an attribute and XmlSerializer does not handle these well. There are a number of workarounds listed here and here. None of them is particularly elegant. The best option might be changing the definition of Id to an element:
public class TrendDatas
{
// ... snip ...
[XmlElement(IsNullable = true)]
public int? Id { get; set; }
public bool ShouldSerializeId() { return Id.HasValue; }
// ... snip ...
}
The ShouldSerializeId is a method that, by convention, the serializer uses to decide if the property should be serialized in the output. In the case of a null value, no element will be defined in the serialized output.

Categories