I have the following C# class
[DataContract(Name = "Person")]
public sealed class Person
{
[DataMember]
public string Name { get; set; }
[DataMember]
public List<int> Numbers { get; set; }
}
The object created with
Person person = new Person
{
Name = "Test",
Numbers = new List<int> { 1, 2, 3 }
};
is serialized to an XML document with the DataContractSerializer:
<Person xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/Workflows.MassTransit.Hosting.Serialization">
<Name>Test</Name>
<Numbers xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:int>1</d2p1:int>
<d2p1:int>2</d2p1:int>
<d2p1:int>3</d2p1:int>
</Numbers>
</Person>
JsonConvert.SerializeXNode(xmlDocument) returns the following JSON:
{
"Person": {
"@xmlns:i": "http://www.w3.org/2001/XMLSchema-instance",
"@xmlns": "http://schemas.datacontract.org/2004/07/Workflows.MassTransit.Hosting.Serialization",
"Name": "Test",
"Numbers": {
"@xmlns:d2p1": "http://schemas.microsoft.com/2003/10/Serialization/Arrays",
"d2p1:int": [
"1",
"2",
"3"
]
}
}
}
When I deserialize the JSON above with JsonConvert.DeserializeObject(json, typeof(Person)) to a POCO both Properties (Name, Numbers) are NULL.
I've already tried to remove the outer object:
{
"@xmlns:i": "http://www.w3.org/2001/XMLSchema-instance",
"@xmlns": "http://schemas.datacontract.org/2004/07/Workflows.MassTransit.Hosting.Serialization",
"Name": "Test",
"Numbers": {
"@xmlns:d2p1": "http://schemas.microsoft.com/2003/10/Serialization/Arrays",
"d2p1:int": [
"1",
"2",
"3"
]
}
}
Then the following exception occurs:
Newtonsoft.Json.JsonSerializationException
HResult=0x80131500
Nachricht = Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[System.Int32]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'Numbers.@xmlns:d2p1', line 6, position 18.
Quelle = Newtonsoft.Json
Stapelüberwachung:
at Newtonsoft.Json.Serialization.JsonSerializerInternalReader.CreateObject(JsonReader reader, Type objectType, JsonContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerMember, Object existingValue)
It seems that the JSON converted from an XML document differs from the JSON directly created from the POCO.
POCO => JSON => POCO works fine
POCO => XML => JSON => POCO The POCO gets NULL properties and/or the exception
Is it possible to configure Json.NET so that it creates compatible JSON documents?