3

I am currently using the Newtonsoft Json.NET library to parse Json encoded data and then later convert nodes to the desired data type.

Here is an example data structure which is already working for me:

{ "ToolUtility": { "SharedBrushListModel": { "SelectedBrushInstanceID": 786 }, "SomethingElse": 42 } } 

And here is how I can interact with this data:

// Parse data and collate into groups of properties. var store = new Dictionary<string, Dictionary<string, JProperty>>(); foreach (var group in JObject.Parse(jsonInput)) { var storeGroup = new Dictionary<string, JProperty>(); store[group.Key] = storeGroup; foreach (var property in group.Value.Children<JProperty>()) storeGroup[property.Name] = property; } // Convert nodes into the desired types. var utilityNode = store["ToolUtility"]; var model = utilityNode["SharedBrushListModel"].ToObject<SharedBrushListModel>(); int somethingElse = utilityNode["SomethingElse"].ToObject<int>(); // Convert desired types back to nodes. var nodeA = JToken.FromObject(model); var nodeB = JToken.FromObject(somethingElse); // Encode back to Json. var outputRoot = new JObject(); outputRoot["ToolUtility"] = new JObject(); outputRoot["ToolUtility"]["SharedBrushListModel"] = nodeA; outputRoot["ToolUtility"]["SomethingElse"] = nodeB; string json = outputRoot.ToString(formatter); 

The nice thing with this API is that I can parse the Json encoded data without including any type annotations, and then explicitly convert nodes into the specialized type at a later time when this has been resolved.

Is there a way with regular .NET to do the same sort of thing with XML?

<?xml version="1.0" encoding="utf-8"?> <root> <ToolUtility> <SharedBrushListModel> <SelectedBrushInstanceID>786</SelectedBrushInstanceID> </SharedBrushListModel> <SomethingElse>42</SomethingElse> </ToolUtility> </root> 

I would like to achieve this using standard .NET libraries rather than requiring any third-party libraries such as Json.NET.

The trouble with including additional libraries is that a number of issues occur in the target environment (Unity game engine) where multiple assets include the same library.

3
  • do you want to parse JSON into XML? Commented May 13, 2014 at 18:44
  • 3
    Look into "Linq to XML" (one example here, the internet has many more examples...) Commented May 13, 2014 at 18:45
  • @ManyRootsofAllEvil Nope, I would like to avoid the JSON step altogether. Commented May 13, 2014 at 18:54

3 Answers 3

4

Check out the System.Xml.Linq namespace. Here is the mapping of concepts:

  • JToken => XNode
  • JToken.Parse(string json) => XDocument.Parse(string xml)
  • JToken.ToObject<T>() => XNode.ToObject<T>() (Extension method shown below)

The ToObject<T> method is not actually on XNode by default. Here is that extension method:

public T ToObject<T>(this XNode node) { var serializer = new XmlSerializer(typeof(T)); using (var reader = node.CreateReader()) { return (T)serializer.Deserialize(reader); } } 
Sign up to request clarification or add additional context in comments.

2 Comments

From the MSDN it would seem that this is indeed what I am looking for. Now I just hope that the version of the Mono framework which Unity uses actually supports this.
If your mono project is targeted 3.5 or higher, then it is supported
3

C# has a built in capability called LINQ To XML. Here's an example of how powerfull the query syntax is:

IEnumerable<XElement> partNos = from item in purchaseOrder.Descendants("Item") where (int) item.Element("Quantity") * (decimal) item.Element("USPrice") > 100 orderby (string)item.Element("PartNumber") select item; 

And you can create XML's using declerative syntax like:

XElement contacts = new XElement("Contacts", new XElement("Contact", new XElement("Name", "Patrick Hines"), new XElement("Phone", "206-555-0144", new XAttribute("Type", "Home")), new XElement("phone", "425-555-0145", new XAttribute("Type", "Work")), new XElement("Address", new XElement("Street1", "123 Main St"), new XElement("City", "Mercer Island"), new XElement("State", "WA"), new XElement("Postal", "68042") ) ) ); 

2 Comments

Anything similar to this to do from objects to Json?
@CesarD Json.NET has LINQ to JSON.
1

If you use classes and define in them the data, you can serialize and deserialize the data (objects of that class) to and from XML:

var serializer = new XmlSerializer(SomeList.GetType()); using (var writer = XmlWriter.Create(SomeFile)) serializer.Serialize(writer, SomeList); 

and

var serializer = new XmlSerializer(typeof(List<SomeClass>)); using (XmlReader reader = XmlReader.Create(SomeFile)) SomeList = (List<SomeClass>)serializer.Deserialize(reader); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.