I have these classes:
public class House
{
public MyObject[] Objects { get; set; }
}
public class MyObject
{
public string Name { get; set; }
}
that I instantiate like this:
var house1 = new House
{
Objects = new MyObject[]
{
new MyObject() { Name = "Name1" },
new MyObject() { Name = "Name2" }
}
};
Then I get its json representation:
var jsonSerializerSettings = new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.Objects
};
string json = JsonConvert.SerializeObject(house1, jsonSerializerSettings);
From the latter I get the relative XML:
XmlDocument doc = (XmlDocument)Newtonsoft.Json.JsonConvert.DeserializeXmlNode(json, "House", true);
string xmlString = doc.OuterXml;
And finally I transform the xml into the object of the initial type:
XmlSerializer serializer = new XmlSerializer(typeof(House));
TextReader reader = new StringReader(xmlString);
House house2 = (House)serializer.Deserialize(reader)
The questions are:
- Why house1 is different from house2? (house2.Objects is empty!)
- What am I doing wrong?
Here you can find a dotnetfiddle example
CodePudding user response:
Generated XML by JSON serializer:
<House xmlns:json="http://james.newtonking.com/projects/json" json:type="Program House, ayusorzt">
<Objects json:type="Program MyObject, ayusorzt">
<Name>
Name1
</Name>
</Objects>
<Objects json:type="Program MyObject, ayusorzt">
<Name>
Name2
</Name>
</Objects>
</House>
XMLSerializer
can't deserailze this XML object. Right XML object should look like this:
<House>
<Objects>
<MyObject>
<Name>
Name1
</Name>
</MyObject>
<MyObject>
<Name>
Name2
</Name>
</MyObject>
</Objects>
</House>
You can fix it by following code:
var xmlSerializer = new XmlSerializer<House>();
var obj = JsonConvert.DeserializeObject<House>();
using(StringWriter textWriter = new StringWriter())
{
xmlSerializer.Serialize(textWriter, obj);
string yourXml = textWriter.ToString();
}
CodePudding user response:
The XML generated by the JsonConvert.DeserializeXmlNode
method is not interoperable with the XmlSerializer
.
In order to deserialize the XML, you need to use Newtonsoft.Json itself
string json2 = JsonConvert.SerializeXmlNode(doc, Newtonsoft.Json.Formatting.None, true);
House house2 = JsonConvert.DeserializeObject<House>(json2);
EDIT
For generating XML from json that works with the XmlSerializer
, deserialize the JSON to an object and then use the XmlSerializer
to generate the XML.
const string json = "{\"Objects\":[{\"Name\":\"Name1\"},{\"Name\":\"Name2\"}]}";
House house = JsonConvert.DeserializeObject<House>(json);
XmlSerializer serializer = new XmlSerializer(typeof(House));
StringBuilder sb = new StringBuilder();
using (XmlWriter writer = XmlWriter.Create(sb))
{
serializer.Serialize(writer, house);
}
//Console.WriteLine(sb.ToString());