Last active
August 29, 2015 14:02
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
http://stackoverflow.com/questions/24368006/how-to-get-json-net-to-serialize-empty-xml-element-to-empty-string