I have the following console application:
using System;
using System.IO;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace OutputApp
{
public class Foo
{
public object Value1 { get; set; }
public string Value2 { get; set; }
}
public class Bar
{
public int Arg1 { get; set; }
public double Arg2 { get; set; }
}
class Program
{
public static Foo CreateFooBar()
{
return new Foo
{
Value1 = new Bar
{
Arg1 = 123,
Arg2 = 99.9
},
Value2 = "Test"
};
}
public static string SerializeXml(object obj)
{
using (var stream = new MemoryStream())
{
using (var reader = new StreamReader(stream))
{
var serializer = new XmlSerializer(obj.GetType());
serializer.Serialize(stream, obj);
stream.Position = 0;
return reader.ReadToEnd();
}
}
}
static void Main(string[] args)
{
var fooBar = CreateFooBar();
var json = JsonConvert.SerializeObject(fooBar, Formatting.Indented);
var xnode = JsonConvert.DeserializeXNode(json, "RootElement");
var xml = xnode.ToString();
var badXml = SerializeXml(fooBar);
Console.ReadLine();
}
}
}
I have two classes. Class Fooand class Bar. A class Foohas a type property object. This is a requirement because it is a contract that can contain many objects, and therefore I cannot set the property for a particular type or general.
Now I create a dummy object fooBarusing the method CreateFooBar(). After that, I first serialize it to JSON, which works fine with Json.Net. Then I use the Jcon.Net XML converter to convert the json string to an object XNode. It works great.
The conclusion of both of them is as follows:
{
"Value1": {
"Arg1": 123,
"Arg2": 99.9
},
"Value2": "Test"
}
<RootElement>
<Value1>
<Arg1>123</Arg1>
<Arg2>99.9</Arg2>
</Value1>
<Value2>Test</Value2>
</RootElement>
Now that this works, it is, of course, not very nice, because I have to serialize in json in order to serialize it in xml later. I would like to serialize directly in xml.
When I use XmlSerializerfor this, I get the infamous InvalidOperationExceptoin because I did not decorate my classes with an attribute XmlIncludeor did not use one of the other workarounds .
InvalidOperationException
Type OutputApp.Bar was not expected. Use XmlInclude or SoapInclude to specify types that are not known statically.
None of the workarounds for XmlSerializer is a good IMHO solution, and I don't see the need for it, since it is quite possible to serialize an object in XML without crappy attributes .
>- Xml- .NET, , Json.Net?
?
Update1
, . XmlInclude, , . , , , . , XmlInclude, Assembly A B. , go!
Update2
, , XmlSerializer, XML- , .
, , object . , . , , XML, .
"" . .NET- (XmlSerializer). - - , . .
( )?