c# - System.Text.Json 到 Newtonsoft Json
问题描述
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;
}
}
解决方案
您可以尝试使用JToken
and JTokenType
:
var tok = JsonConvert.DeserializeObject<JToken>("{\"test\": 1}"); // or JToken.Parse
Console.WriteLine(tok.Type); // prints "Object"
推荐阅读
- docker - 我无法从 docker 容器连接到代理
- angular - Firebase 部署错误:“malloc:无法分配区域”或“分段错误:11”
- python - mingw32-gcc 编译 Cython 输出:pyconfig.h 的未知多架构位置(和其他警告)
- javascript - b-list-group-item 中的 v-bind 在带有 bootstrap-vue 的 vue CLI-app 中不起作用
- android - 如何在RelativeLayout的中心对齐和对齐内容?
- linux - 如何获取所有 PCI 设备的供应商 ID 和设备 ID?
- dictionary - 更新 Kotlin 中特定键的映射值
- c - 如何在 C 中的正弦函数中输入高于 122.409 的角度
- excel - 将多行从一个文件附加到另一个文件
- java - 将 UUID 与 Spring 引导数据一起使用