我正在使用一个大的Json文件(使用Json.NET)。 我将我的JObject转换为Dictionnary。现在我试图恢复它以便能够通过值获取密钥。问题是Json文件很复杂,我不知道如何处理它。 以下是json文件的示例:
{
"MASTER_MODE": {
"SET_VTSA": {
"id": 10,
"position": 24,
"elements": {
"SET_CAV_Vol": {
"id": 0,
"formatted_lenght": 2,
"format_divider": 1,
"is_included_in_integrity_checksum": true,
"is_signed": false
},
"SET_ALARM_VOLTAGE_MAX": {
"id": 29,
"formatted_lenght": 1,
"format_divider": 1,
"is_included_in_integrity_checksum": true,
"is_signed": false
}
}
}
},
"MASTER_BASE": {
"SET_MAIN": {
"id": 11,
"elements": {
"SET_Speed": {
"id": 0,
"display_unit": "UNIT_RPM",
"position": 101,
"is_included_in_integrity_checksum": true,
"is_signed": false
},
"Master_Test": {
"id": 3,
"position": 104,
"is_included_in_integrity_checksum": true,
"is_signed": false
}
}
},
"GLOBAL": {
"id": 14,
"elements": {
"SET_Is_Alarm": {
"id": 0,
"type": "bool",
"is_included_in_integrity_checksum": true,
"is_signed": false
},
"SET_Is_Sync": {
"id": 1,
"type": "bool",
"available_in_mode": [
"SET_Vone",
"SET_VdO"
],
"is_included_in_integrity_checksum": true,
"is_signed": false
}
}
},
"MASTER_COMMAND": {
"CMD_GET_COMM_API": {
"id": 1
},
"CMD_START": {
"id": 2
}
},
"MASTER_CONSTANTS": {
"NB_OF_RX_FRAME_BYTES_MIN": 2,
"NB_OF_RX_FRAME_BYTES_MAX": 140,
"FIRST_ANSWER_ID": 120,
"LAST_ANSWER_ID": 135,
"FIRST_EVENT_ID": 195,
"LAST_EVENT_ID": 205,
"NB_OF_SYSTEM_EVENT_LOG_BYTES": 64,
"MAX_SYSTEM_EVENT_LOG_INDEX": 4598
}
}
我已经用Python做过了:
def revert_dictionnary(self, normal_dictionnary):
reverted_dictonnary = {}
try:
for category in normal_dictionnary.items():
reverted_dictonnary[category[0]] = {}
for element in category[1].items():
if category[0] != "DRV_EVENT_SYSTEM" :
reverted_dictonnary[category[0]][
element[1]["id"]] = {"label": element[0]}
if category[0] in ("DRV_SLAVE"):
reverted_dictonnary[category[0]][
element[1]["id"]]["elements"] = {}
for base_element in element[1]["elements"].items():
reverted_dictonnary[category[0]][element[1]["id"]]["elements"][ base_element[1]["id"]] = {"label": base_element[0]}
但我想我在Json.NET或.Net框架中遗漏了一些东西。
你会怎样在C#中做到这一点?
我尝试了两种方式:
public static TKey FindKeyByValue<TKey, TValue>(this IDictionary<TKey, TValue> dictionary, TValue value)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
foreach (KeyValuePair<TKey, TValue> pair in dictionary)
if (value.Equals(pair.Value)) return pair.Key;
throw new Exception("the value is not found in the dictionary");
}
public static IDictionary<string, object> RevertDictionary<TKey, TValue>(this IDictionary<TKey, TValue> dict)
{
IDictionary<TKey, TValue> newDict = new Dictionary<TKey, TValue>();
IDictionary<TKey, TValue> emptyDict = new Dictionary<TKey, TValue>();
foreach (KeyValuePair<TKey, TValue> pair in dict)
{
newDict.Add(pair.Key, (TValue)emptyDict);
// foreach (KeyValuePair<TKey, TValue> elements in pair.Value)
// {
//}
}
return new Dictionary<string, object>();
}
第一次返回null,第二次无效,因为我无法迭代KeyValueMap