{
"odata.error":{
"code":"","message":{
"lang":"en-US","value":"An error has occurred."
},"innererror":{
"message":"\u672a\u88ab\u6388\u6743\u8bbf\u95ee","type":"System.Exception","stacktrace":" \u5728 MvcApplication1.FXAuthorizeAttribute.OnAuthorization(HttpActionContext actionContext) \u4f4d\u7f6e f:\\MyWork.Temp\\MvcApplication1\\MvcApplication1\\App_Start\\WebApiConfig.cs:\u884c\u53f7 50\r\n \u5728 System.Web.Http.Tracing.Tracers.AuthorizationFilterAttributeTracer.<>c__DisplayClass4.<OnAuthorization>b__1()\r\n \u5728 System.Web.Http.Tracing.ITraceWriterExtensions.TraceBeginEnd(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String operatorName, String operationName, Action`1 beginTrace, Action execute, Action`1 endTrace, Action`1 errorTrace)\r\n \u5728 System.Web.Http.Tracing.Tracers.AuthorizationFilterAttributeTracer.OnAuthorization(HttpActionContext actionContext)\r\n \u5728 System.Web.Http.Filters.AuthorizationFilterAttribute.System.Web.Http.Filters.IAuthorizationFilter.ExecuteAuthorizationFilterAsync(HttpActionContext actionContext, CancellationToken cancellationToken, Func`1 continuation)"
}
}
}
上面是用DataServiceContext访问webapi odata时的异常, 现在需要把这段json反序列化成object或dynamic或其他什么都可以, 用
string json = ex.InnerException.Message;
dynamic task = JObject.Parse(json);
var dyn = JsonConvert.DeserializeObject<dynamic>(json);
可以得到task或dyn这两个动态对象, 现在应该怎么从这些对象中取值?
注意, json最外层那个字段名, "odata.error",
可以这样取:
task["odata.error"]["message"]["value"]
哥, 你太牛逼了, 顺便再来一个实体类的呗?
是不是没法定义实体类了呀?
@kingcomxu:
有办法定义实体类,详见下面的代码:
public class Innererror { public string message { get; set; } } public class Message { public string lang { get; set; } public string value { get; set; } public Innererror innererror { get; set; } } public class OdataError { public string code { get; set; } public Message message { get; set; } } public class Q_55777 { [Fact] public void Test() { var json = "{\"odata.error\":{\"code\":\"\",\"message\":"+ "{\"lang\":\"en-US\",\"value\":\"An error has ccurred.\"}," +"\"innererror\":{\"message\":\"error\"}}}"; var dyn = JsonConvert.DeserializeObject<Dictionary<string, OdataError>>(json); Console.WriteLine(dyn["odata.error"].message.value); } }