【发布时间】:2020-09-04 02:11:36
【问题描述】:
newtonsoft Json 中是否有 JsonElement 和 JsonValueKind 等价物?将以下使用 System.Text.Json 的代码移植到 newtonsoft Json 的正确代码是什么?由于我的 dll 无法找到正确的 System.Buffers 程序集版本而导致我的移植的原因。我遵循了所有我能得到的建议,但我仍然无法解决它。所以想到了使用 Newtonsoft Json。
public static Dictionary<string, dynamic> JsonDeserialize(string Json)
{
JsonElement elm = JsonSerializer.Deserialize<JsonElement>(Json);
Dictionary<string, dynamic> dict = ElementToDict(elm);
return dict;
}
public static dynamic ElementToDict(JsonElement obj)
{
if (obj.ValueKind == JsonValueKind.Number)
{
return StringToDecimal(obj.GetRawText());
}
else if (obj.ValueKind == JsonValueKind.String)
{
return obj.GetString();
}
else if (obj.ValueKind == JsonValueKind.True || obj.ValueKind == JsonValueKind.False)
{
return obj.GetBoolean();
}
else if (obj.ValueKind == JsonValueKind.Object)
{
var map = obj.EnumerateObject().ToList();
var newMap = new Dictionary<String, dynamic>();
for (int i = 0; i < map.Count; i++)
{
newMap.Add(map[i].Name, ElementToDict(map[i].Value));
}
return newMap;
}
else if (obj.ValueKind == JsonValueKind.Array)
{
var items = obj.EnumerateArray().ToList();
var newItems = new ArrayList();
for (int i = 0; i < items.Count; i++)
{
newItems.Add(ElementToDict(obj[i]));
}
return newItems;
}
else
{
return null;
}
}
【问题讨论】: