我想带一些Json并将其解析为一组键/值对,但有些值本身就是字典。我尝试了通常的Newtonsoft反序列化。它很接近,但不是很正确。最终结果必须是字典,而不是强类型类。
这是Json的一些例子:
{
"JobNumber": 1010,
"Asset": null,
"JobNotes": [
{
"NoteText": "It's not working.",
"NoteType": "Complaint"
},
{
"NoteText": "Needs to be fixed",
"NoteType": "Job"
}
]
}
这是我用来反序列化的代码:
var json = File.ReadAllText(@"c:\temp\job.json");
var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
结果几乎是正确的,但带有“JobNotes”键的项的值只是json字符串。我希望解析器递归并将内部Json反序列化为另一个字符串和对象字典。 有没有办法可以用Newtonsoft库做到这一点?或者,是否有其他库可以解决这个问题?我可以挂钩解析方法来覆盖那个时间点的功能吗?
答案 0 :(得分:1)
这可以通过一点递归来完成。我会将IsJson
定义为学术练习。 :)
Dictionary<string, object> RecursiveDeserialize(string json)
{
var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
foreach (var pair in result.ToArray())
{
if(IsJson(pair.Value))
{
result[pair.Key] = RecursiveDeserialize(pair.Value);
}
}
return result;
}
答案 1 :(得分:1)
这是@ DanielKeogh代码的修改版本。效果很好。
class Program
{
static void Main(string[] args)
{
var json = File.ReadAllText(@"c:\temp\job3.json");
var result = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
RecurseDeserialize(result);
}
private static void RecurseDeserialize(Dictionary<string, object> result)
{
//Iterate throgh key/value pairs
foreach (var keyValuePair in result.ToArray())
{
//Check to see if Newtonsoft thinks this is a JArray
var jarray = keyValuePair.Value as JArray;
if (jarray != null)
{
//We have a JArray
//Convert JArray back to json and deserialize to a list of dictionaries
var dictionaries = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(jarray.ToString());
//Set the result as the dictionary
result[keyValuePair.Key] = dictionaries;
//Iterate throught the dictionaries
foreach (var dictionary in dictionaries)
{
//Recurse
RecurseDeserialize(dictionary);
}
}
}
}
}
这个经过修改的Json显示了它的深度:
{
"JobNumber": 1010,
"Asset": null,
"JobNotes": [
{
"NoteText": "It's not working.",
"NoteType": "Complaint"
},
{
"NoteText": "Needs to be fixed",
"NoteType": "Job",
"JobNoteNotes": [
{
"Something": 1,
"Something2": "Test"
}
]
}
]
}
结果会结束三个字典,这样我就可以按键获得“Something”值。
答案 2 :(得分:-1)
将此对象用于json字符串
public class JobNote
{
public string NoteText { get; set; }
public string NoteType { get; set; }
}
public class ListJob
{
public int JobNumber { get; set; }
public object Asset { get; set; }
public List<JobNote> JobNotes { get; set; }
}
&#13;
然后你可以反序列化它