c# – 可以查找Json.net中不存在的Key

前端之家收集整理的这篇文章主要介绍了c# – 可以查找Json.net中不存在的Key前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有几种不同的格式进来,但我无法弄清楚如何处理它们,因为当我尝试找到关键json.net崩溃.我希望它只会返回null.
foreach (var item in jsonObj)
{
    var msg = item.Value["Msg"];
    if (msg != null)
    {
       txtErrors.Text += msg + Environment.NewLine;
    }
}

//格式一

{[UserNotFound,{
  "SeverityType": 3,"ValidationType": 2,"Msg": "Email Not Found"
}]}

我的代码工作.

//格式2(来了,因为我没有在服务器端捕获异常)

{
  "Message": "An error has occurred.","ExceptionMessage": "Object reference not set to an instance of an object.","ExceptionType": "System.NullReferenceException","StackTrace": "  "
}

我当然可以解决这个问题,并抓住这个例外.但是,如果我再次忘记,我也不会在客户端上崩溃.所以我很想打印出“消息”,但是我没有得到如何做,所以它不会崩溃在var msg = item.Value [“Msg”];

我尝试做var msg = item.Value [“Msg”]时得到的错误;

System.InvalidOperationException was unhandled
  Message=Cannot access child value on Newtonsoft.Json.Linq.JValue.
  StackTrace:
       at Newtonsoft.Json.Linq.JToken.get_Item(Object key)
       at Fitness.WindowsPhone7.UI.MainPage.<btnSignIn_Click>b__0(IRestResponse response)
       at RestSharp.RestClientExtensions.<>c__DisplayClass1.<ExecuteAsync>b__0(IRestResponse response,RestRequestAsyncHandle handle)
       at RestSharp.RestClient.ProcessResponse(IRestRequest request,HttpResponse httpResponse,RestRequestAsyncHandle asyncHandle,Action`2 callback)
       at RestSharp.RestClient.<>c__DisplayClass3.<ExecuteAsync>b__0(HttpResponse r)
       at RestSharp.RestClient.<>c__DisplayClass5.<>c__DisplayClass7.<ExecuteAsync>b__2(Object s)
       at System.Reflection.RuntimeMethodInfo.InternalInvoke(RuntimeMethodInfo rtmi,Object obj,BindingFlags invokeAttr,Binder binder,Object parameters,CultureInfo culture,Boolean isBinderDefault,Assembly caller,Boolean verifyAccess,StackCrawlMark& stackMark)
       at System.Reflection.RuntimeMethodInfo.InternalInvoke(Object obj,Object[] parameters,StackCrawlMark& stackMark)
       at System.Reflection.MethodBase.Invoke(Object obj,Object[] parameters)
       at System.Delegate.DynamicInvokeOne(Object[] args)
       at System.MulticastDelegate.DynamicInvokeImpl(Object[] args)
       at System.Delegate.DynamicInvoke(Object[] args)
       at System.Windows.Threading.DispatcherOperation.Invoke()
       at System.Windows.Threading.Dispatcher.Dispatch(DispatcherPriority priority)
       at System.Windows.Threading.Dispatcher.OnInvoke(Object context)
       at System.Windows.Hosting.CallbackCookie.Invoke(Object[] args)
       at System.Windows.Hosting.DelegateWrapper.InternalInvoke(Object[] args)
       at System.Windows.RuntimeHost.ManagedHost.InvokeDelegate(IntPtr pHandle,Int32 nParamCount,ScriptParam[] pParams,ScriptParam& pResult)

解决方法

假设你使用Newtonsoft.Json:

您可以使用JObject测试是否有属性

JObject jObj; //initialized somewhere,perhaps in your foreach
var msgProperty = jObj.Property("msg");

//check if property exists
if (msgProperty != null) {
    var mag = msgProperty.Value;
} else {
    //there is no "msg" property,compensate somehow.
}

猜你在找的C#相关文章