Smart way of changing json conversion to xml and keep setup - c#

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.

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

Related

How to dynamically create a JSON object in c# (from an ASP.NET resource file)?

I need to serialize the strings from a resource file (.resx) into a JSON object. The resource file's keys are in flux and thus I cannot just create a C# object that accepts the appropriate values. It needs to be a dynamic solution. I am able to loop through the key-value pairs for the file, but I need an easy way to serialize them to JSON.
I know I could do:
Object thing = new {stringOne = StringResource.stringOne; ...}
But, I'd rather have something like:
Object generic = {}
foreach (DictionaryEntry entry in StringResource) {
generic.(entry.Key) = entry.Value
}
Or should I just create a custom JSON serializer that constructs the object piecemeal (i.e. foreach loop that appends part of the JSON string with each cycle)?
EDIT
I ended up writing a quick JSON serializer that constructs the string one field at a time. I didn't want to include a whole JSON library as this is the only use of JSON objects (for now at least). Ultimately, what I wanted is probably impractical and doesn't exist as it's function is better served by other data structures. Thanks for all the answers though!
If you're using C# 4.0, you should look at the magical System.Dynamic.ExpandoObject. It's an object that allows you to dynamically add and remove properties at runtime, using the new DLR in .NET 4.0. Here is a good example use for the ExpandoObject.
Once you have your fully populated ExpandoObject, you can probably easily serialize that with any of the JSON libraries mentioned by the other excellent answers.
This sounds like an accident waiting to happen (i.e. creating output prior to cementing the structure), but it happens.
The custom JSON serializer is a compelling option, as it allows you to easily move from your dictionary into a JSON format. I would look at open source libraries (JSON.NET, etc) to see if you can reduce the development time.
I also think setting up in a slightly more structured format, like XML, is a decent choice. It is quite easy to serialize from XML to JSON using existing libraries, so you avoid heavy customization/
The bigger question is what purposes will the data ultimately serve. If you solve this problem using either of these methods, are you creating bigger problems in the future.
Probably I would use JSON.NET and the ability to create JSON from XML.
Then, you could create an XML in-memory and let JSON.NET convert it to JSON for you. Maybe if you dig deeper into the API, there are other options, too.
Newtonsoft is a library that has all kinds of nifty JSON tools...among them, on-the-fly one-line serializer and deserializers...check it out, it's my favorite JSON library out there
http://james.newtonking.com/pages/json-net.aspx
If I remember correctly, it has a class that will convert JSON to a .NET object without having to create the .NET object first. Think it is in the Json.Convert class
The way I do it is:
var serialiser = new System.Web.Script.Serialization.JavaScriptSerializer();
string json = serialiser.Serialize(data);
context.Response.Write(json);

Deserialize XML with different schemas into a shared type

Using c#, I want to deserialize xml from various sources into objects of a common type. The XML will not have the same schema. Eg, in the following xml, /thingContainer/thing/name and widget/#title both would map to myClass.DisplayName.
Xml1:
<thingContainer>
<thing>
<name>MyName</name>
</thing>
</thingContainer>
Xml2:
<widget title="myTitle" />
So, I can't mark up my class with [XmlElement], since it will be different depending on the source of my xml. Is there some trick I can do with inheritance or some helper class that will enable me to easily deserialize xml from different sources? Is there some easy way to map class fields to xpaths?
Of course, if I have to, I'll parse and manually deserialize the xml... but what fun is that?
Two thoughts that immediately spring to mind:
Use XSLT to transform the original XML into an interim format that matches your object model (a very popular approach, though personally I despise XSL)
Create interim object models to deserialize to, then map them to your final object model.
There's probably some XmlElement hackery possible, but it seems like it would be a messy approach.
I think you have two options here:
Implement IXmlSerializable for your class and deserialize taking into account the structure of your XML
Just use LINQ to XML to parse the XML and create an instance of your class. This is the approach I would pick (having gone through the first choice myself and not liking it)

Write CLR objects to XML with LINQ

I have an ObservableCollection items. I want to convert these to XML format so that I can store them for later use. I'm a little new to LINQ and I'm not sure how to do this. I know that I need to rely on the XDocument. But I'm not sure how to execute the query and get the results into a string format.
Can somebody please provide some pointers for me? It just seems like such an easy task, I'd be surprised if it couldn't be done.
Thank you,
You need Linq to XML. I can't post a real code here since I don't know the structure of your data, but here's a dummy example:
List<Person> people = ...
var doc = new XDocument(
new XElement("People",
from p in people
select new XElement("Person",
new XAttribute("Id", p.Id),
new XElement("LastName", p.LastName),
new XElement("FistName", p.FirstName))));
doc.Save("people.xml");
Note that Linq is not the only option here. Another very good approach is XML serialization.
Using the DataContractSerializer is your best bet. It's designed to do exactly what you are asking for.
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.datacontractserializer(v=VS.95).aspx
Advantages over XMLSerializer:
Opt-in rather than opt-out properties to serialize. This mean you specify what you want serialize
Because it is opt in you can serialize not only properties, but also fields. You can even serialize non-public members such as private or protected members. And you dont need a set on a property either (however without a setter you can serialize, but not deserialize)
Is about 10% faster than XmlSerializer to serialize the data because since you don’t have full control over how it is serialize, there is a lot that can be done to optimize the serialization/deserialization process.
Can understand the SerializableAttribute and know that it needs to be serialized
More options and control over KnownTypes
Disadvantages:
No control over how the object is serialized outside of setting the name and the order
I'm not sure what you want.
You can create a XElement and convert it to a string with the ToString method.
You can do the same with XDocument.
I'm not at all familiar with Silverlight, but it sounds like you are going to need to use XML serialization. XML serialization allows you to serialize an object into an XML representation, which you can then later deserialize from XML back into an object.
Here are some tutorials and information on XML serialization in .NET:
XML Serialization
XML Serialization Using C#
XmlSerializer class

Creating something similar to System.ServiceModel.Syndication using .NET 3.5

If I am dealing with several standard xml formats what would be the best practice way of encapsulating them in C# 3.5? I'd like to end up with something similar to the System.ServiceModel.Syndication namespace.
A class that encapsulates the ADF 1.0 XML standard would be one example. It has the main XML root node, 6 child elements, 4 of which are required IIRC, several required and optional elements and attributes further down the tree. I'd like the class to create, at a minimum, the XML for all the required pieces all the way up to a full XML representation. (Make sense).
With LINQ 4 XML and extension classes, etc, etc, there has to be some ideas on quickly generating a class structure for use. Yes? No? :)
Am not sure if I gave enough details to get one correct answer but am willing to entertain ideas right now.
TIA
XML serialization seems a good approach. You could even use xsd.exe to generate the classes automatically...
EDIT
Note that the class names generated by the tool are usually not very convenient, so you might want to rename them. You might also want to change arrays of T to List<T>, so that you can easily add items where needed.
Assuming the class for the root element is named ADF, you can load an ADF document as follows :
ADF adf = null;
XmlSerializer xs = new XmlSerializer(typeof(ADF));
using (XmlReader reader = XmlReader.Create(fileName))
{
adf = (ADF)xs.Deserialize(reader);
}
And to save it :
ADF adf = ...; // create or modify your document
...
XmlSerializer xs = new XmlSerializer(typeof(ADF));
using (XmlWriter writer = XmlWriter.Create(fileName))
{
xs.Serialize(writer, adf);
}
Why not just follow the pattern of the SyndicationFeed object in the Syndication namespace? Create a class that takes in a Uri to the xml document or just takes in the document fragment.
Then parse the document based on your standards (this parsing can be done using LinqToXml if you wanted to, though regEx might be faster if you are comfortable with them). Throw exceptions or track errors appropriately when the document doesn't pass the specification rules.
If the document passes the parse step then break the pieces of the document out into public getter properties of your object. Then return the fully hydrated object back to the consumer for use
Seems pretty straight forward to me. Is that what you are after or are you looking for something more than this?

How can I make XmlSerializer.Deserialize more strict?

I have some very similar XML structures which are in fact quite distinct, but it appears that XmlSerializer.Deserialize is very "forgiving" and will go out of its way to take XML and deserialize out into a strongly typed object I created from the source XSDs. Is there any way to make it more strict or do some type of deeper validation?
// Locals
var serializer = new XmlSerializer(typeof(SomeCustomType));
// Set
var someInstance = serializer.Deserialize(new StringReader(xmlString.ToString()))
#Jeff Because the root nodes are similar it will deserialize into completely different objects. Imagine that you have a house, car and boat and they all share a base root node called item with a few attributes. Even though sub-nodes are invalid and unshared it seems to overlook and forgive that.
#Will I don't want to validate against the XSD. I want to somehow cause the Deserializer to see that the data it has shouldn't be shoe-horned into the wrong Object type.
The problem was that the XML input was incorrect.
I once used validating reader to validate XML against schema as I read it into the deserializer.

Categories