如何JSON.Net投JObject至T [英] How to cast JObject in JSON.Net to T

查看:184
本文介绍了如何JSON.Net投JObject至T的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,我可以使用JsonConvert.DeserializeObkect(串),但是,我需要不期而遇的对象_type(可能不是第一个参数),以determin特定的类转换为。从本质上讲,我所想要做的是一样的东西...

  //通用JSON处理器的API客户端。 
功能MyBaseType ProcessJson(字符串jsonText)
{
VAR OBJ = JObject.Parse(jsonText);
开关(obj.Property(_型)Value.ToString()){
案sometype。这时候:
返回obj.RootValue< MyConcreteType>();
//注意:这不起作用......
//返回obj.Root.Value();

}
}
...

//我的使用...
VAR OBJ = ProcessJson(jsonText) ;
无功实例= OBJ为MyConcreteType;
如果(例如== NULL)抛出新MyBaseError(OBJ);


解决方案

首先解析JSON成JObject。然后查找使用LINQ to JSON的 _type 属性。然后切换取决于价值和铸造用 ToObject< T>

 变种O = JObject.Parse(文本); 
VAR jsonType =(字符串)O [_型];

开关(jsonType){
案东西:返回o.ToObject<类型和GT;();

}


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

//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();
    ...
  }
}
...

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

解决方案

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

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

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

这篇关于如何JSON.Net投JObject至T的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆