Skip to content

Instantly share code, notes, and snippets.

@jonelf
Last active August 29, 2015 14:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonelf/47e3a1b2f06b66983e29 to your computer and use it in GitHub Desktop.
Save jonelf/47e3a1b2f06b66983e29 to your computer and use it in GitHub Desktop.
Serializes POCO to XML. Converts it to Json with Json.NET. Parses it to a JObject and queries it with SelectToken. This turns an empty string to null.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Serialization;
using CSScriptLibrary;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace ConsoleApplication1
{
[Serializable]
public class Serializetest
{
public Serializetest()
{
Empty = string.Empty;
}
public string Empty { get; set; }
}
class Program
{
static void Main(string[] args)
{
var serializetest = new Serializetest();
string xmlText;
var serializer = new XmlSerializer(typeof(Serializetest));
using (StringWriter textWriter = new StringWriter())
{
using (XmlWriter xmlWriter = XmlWriter.Create(textWriter))
{
serializer.Serialize(xmlWriter, serializetest);
}
xmlText = textWriter.ToString();
}
var doc = new XmlDocument();
doc.LoadXml(xmlText);
var jsonText = JsonConvert.SerializeXmlNode(doc);
var xmlFromJson = JsonConvert.DeserializeXmlNode(jsonText);
// Back to XML it's "" again.
var objectFromJson = JsonConvert.DeserializeObject<Serializetest>(jsonText);
// Correctly deserialized to ""
// I want to access the Json directly
var json = JObject.Parse(jsonText);
var empty = (string)json.SelectToken("Serializetest.Empty");
// null, this is the problem.
var dynamicObj = JsonConvert.DeserializeObject<dynamic>(jsonText);
var t = (string)dynamicObj.Serializetest.Empty;
// t is also null
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment