首页 新闻 会员 周边 捐助

一个json的反序列化, Newtonsoft, 属性名带一个点.................

0
悬赏园豆:80 [已解决问题] 解决于 2013-10-15 10:59

{
"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", 

kingcomxu的主页 kingcomxu | 初学一级 | 园豆:4
提问于:2013-10-15 10:19
< >
分享
最佳答案
0

可以这样取:

task["odata.error"]["message"]["value"]
收获园豆:40
dudu | 高人七级 |园豆:30939 | 2013-10-15 10:26

哥, 你太牛逼了, 顺便再来一个实体类的呗?

是不是没法定义实体类了呀?

kingcomxu | 园豆:4 (初学一级) | 2013-10-15 10:35

@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);
    }
}
dudu | 园豆:30939 (高人七级) | 2013-10-15 11:16
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册