C# 如何将 JSON.Net 中的 JObject 转换为 T

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10218827/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 12:56:23  来源:igfitidea点击:

How to cast JObject in JSON.Net to T

c#jsoncastingjson.net

提问by Tracker1

I know that I can use JsonConvert.DeserializeObject<T>(string), however, I need to peek into the object's _type(which may not be the first parameter) in order to determine the specific class to cast to. Essentially, what I am wanting to do is something like:

我知道我可以使用JsonConvert.DeserializeObject<T>(string),但是,我需要查看对象的_type(可能不是第一个参数)以确定要转换到的特定类。本质上,我想做的是:

//Generic JSON processor for an API Client.
function MyBaseType ProcessJson(string jsonText)
{
  var obj = JObject.Parse(jsonText);
  switch (obj.Property("_type").Value.ToString()) {
    case "sometype":
      return obj.RootValue<MyConcreteType>();
      //NOTE: this doesn't work... 
      // return obj.Root.Value<MyConcreteType>();
    ...
  }
}
...

// my usage...
var obj = ProcessJson(jsonText);
var instance = obj as MyConcreteType;
if (instance == null) throw new MyBaseError(obj);

采纳答案by yamen

First parse the JSON into a JObject. Then lookup the _typeattribute using LINQ to JSON. Then switch depending on the value and cast using ToObject<T>:

首先将 JSON 解析为 JObject。然后_type使用 LINQ to JSON查找属性。然后根据值切换并使用ToObject<T>

var o = JObject.Parse(text);
var jsonType = (String)o["_type"];

switch(jsonType) {
    case "something": return o.ToObject<Type>();
    ...
}

回答by JotaBe

JSON.NET has no direct ability to support both requisites:

JSON.NET 没有直接支持这两个必要条件的能力:

  • custom name of the property holding the type name
  • look for the property anywhere in the object
  • 保存类型名称的属性的自定义名称
  • 在对象的任何地方查找属性

The first requisites is fulfilled by JsonSubTypesThe second one by specifying thh right MetadataPropertyHandling

第一个要求由JsonSubTypes满足 第二个要求通过指定正确的MetadataPropertyHandling