我目前正在使用Newtonsoft Json.NET库来解析Json编码数据,然后将节点转换为所需的数据类型。
这是一个已经对我有用的示例数据结构:
{
"ToolUtility": {
"SharedBrushListModel": {
"SelectedBrushInstanceID": 786
},
"SomethingElse": 42
}
}
以下是我如何与这些数据进行交互的方法:
// 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);
这个API的好处是我可以解析Json编码数据,而无需包含任何类型注释,然后在稍后解决此问题时将节点显式转换为专用类型。
有没有一种使用常规.NET与XML做类似事情的方法?
<?xml version="1.0" encoding="utf-8"?>
<root>
<ToolUtility>
<SharedBrushListModel>
<SelectedBrushInstanceID>786</SelectedBrushInstanceID>
</SharedBrushListModel>
<SomethingElse>42</SomethingElse>
</ToolUtility>
</root>
我想使用标准的.NET库来实现这个,而不需要任何第三方库,比如Json.NET。
包含其他库的问题在于,目标环境(Unity游戏引擎)中会发生许多问题,其中多个资产包括相同的库。