0

I have already deserialized a json-file to c#-objects. This has been done by the following:

JsonSerializer<FooClass>().DeserializeFromString(json)

and it all works well. I now want to change the json to xml and do the exact same, keeping all the classes and setup, that has already been made inside the solution.

The conversion from json to xml is easy, but I cant figure out how to deserialize the xml so that I dont need to change a lot of code.

Is it possible to keep the whole setup, but somehow change few lines of code such as

JsonSerializer<FooClass>().DeserializeFromString(json)

to something alike, but that deserializes the xml instead? I've found the following solutions in here, but they don't seem to solve the problem:

XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);

but the SerializeXmlNode isn't possible?

The other solutions I have found in here use arguments and stuff like that, which again will force me to change some of the setup, which I am not interested in, if possible.

Also I am aware, that a direct transformation from json to xml has its cons, but if we look aside from that and focus on the xml part, then it would be nice.

This because we are writing in xml instead of json from now on and therefore the change needed.

nelion
  • 1,712
  • 4
  • 17
  • 37
  • Your question isn't really specific. Are you just looking for [How to Deserialize XML document](https://stackoverflow.com/q/364253) and/or [How to serialize/deserialize simple classes to XML and back](https://stackoverflow.com/q/3356976)? – dbc Apr 15 '19 at 21:35
  • @dbc I know how to deserialize XML documents from scratch. The thing is, that I have already written many classes, the solution is already made so it can handle taking in json-files and react to that, and now we suddenly want to use xml-files instead of json-files. Therefore I was just wondering if there was a way to somehow switch the `JsonSerializer().DeserializeFromString(json)` to one or 2 lines of code that takes a xml-file instead and making me able to keep the rest of the solution as it is, not needing to write attributes, etc. - maybe your second link is an option. – nelion Apr 16 '19 at 06:21

1 Answers1

1

One easy route I can see is to leverage the XmlClass Attributes and use XmlSerializer.

C1rdec
  • 1,647
  • 1
  • 21
  • 46
  • Hi @C1rdec - attributes shouldn't be necessary, should they? And how should ´XmlSerializer s = new XmlSerializer(typeof(MyClass), myRoot);´ be used in this context? the xml file is called FromXml.xml and is just an "translation" of the json-file. – nelion Apr 15 '19 at 21:06