列出Json Parse错误,检测部分对象JSON格式错误 - Aspnet Webapi

时间:2017-04-19 08:44:29

标签: c# json asp.net-web-api

我有一个班级

Sub ProcOne()
    OpColOne = 4

    TextColMain = 1
    OpColMain = 2

    i = 1

    Do Until i > 3
        If Cells(i, OpColMain) = "op1" Then
            Cells(2, OpColOne) = Cells(2, OpColOne) & vbNewLine & Cells(i, TextColMain)
            i = i + 1
        End If
    Loop
End Sub

我正在使用class Sample { public string str1; public string str2; public string str3; public string str4; public DateTime date1; public DateTime date2; } 方法,需要解析正文,

通常,如果正文的JSON格式有很大的错误,例如在开头没有括号:

Aspnet Webapi Http Post

使用[ "str1": "32226","str2":"ABC","str3" :"91492","str4":"AC","date1":"1997-04-23T18:25:43", "date2":"1997-04-23T18:25:43" }, {"str1": "3226","str2":"ABF","str3" :"492","str4":"AB","date1":"1997-04-23T18:25:43","date2":"1997-04-23T18:25:43" } ] 解析正文时,您将获得[FromBody]List<Sample> samples,因此您可以使用null来判断正文的json格式是错误的,

但是当我尝试制作一个属性的DateTime JSON格式错误时,例如下面第一个对象中的date2:

samples = null

然后使用[ {"str1": "32226","str2":"ABC","str3" :"91492","str4":"AC","date1":"1997-04-23T18:25:43", "date2":"1997-04-2325:43" -> date2 error datetime string }, {"str1": "3226","str2":"ABF","str3" :"492","str4":"AB","date1":"1997-04-23T18:25:43","date2":"1997-04-23T18:25:43" } ] 进行解析,它可以成功解析第二个[FromBody]List<Sample> samples对象,并显示Sample的列表计数等于1,

但是我没有任何异常或信息可以告诉我第一个对象是JSON解析失败,如果两个对象都被正确解析将使samples计数为2

我尝试将DateTime Type更改为DateTime?但是,它只是解析了第二个对象,并且第一个对象被静默省略。

有没有办法检测到这种错误,只有部分对象的JSON格式是错误的?

我认为一个简单的方法是计算char samples当前时间,并与列表计数进行比较,如果{的计数&lt;列表计数,然后必须有一些对象没有成功解析,但它似乎不是一个好方法。

1 个答案:

答案 0 :(得分:1)

but there isn't any exception or information I can tell that the first object's is JSON Parsed Failed

是的,有一种方法可以查看JSON是否解析了错误

Application_Start()中的

 只需执行以下操作

 protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
        GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Error +=
            delegate(object sender, ErrorEventArgs args)
            {

                File.WriteAllText(@"c:\\temp\\jsonerrortest.txt", args.ErrorContext.Error.Message);                                    

            };   
    }

<强>更新

来自你的评论:

Is there way to tell during the execution? I want to tell the parsed error in the post method and throw an exception inform the user that the input body is wrong.

是的,这样做你必须用DelegatingHandler拦截你的乱七八糟 如下所示:

public  class MessageHandler : DelegatingHandler
{

    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {

        string requestInfo = string.Empty;



            requestInfo = string.Format("{0}:{1}", request.Method, request.RequestUri);
            var requestMessage = await request.Content.ReadAsByteArrayAsync();
            IncommingMessageAsync( requestInfo, requestMessage);


        var response = await base.SendAsync(request, cancellationToken);

            byte[] responseMessage;

            if (response.IsSuccessStatusCode)
            {
                if (response.Content != null)
                    responseMessage = await response.Content.ReadAsByteArrayAsync();
                else
                    responseMessage = Encoding.UTF8.GetBytes(response.ReasonPhrase);

            }
            else
                responseMessage = Encoding.UTF8.GetBytes(response.ReasonPhrase);          
            OutgoingMessageAsync( requestInfo, responseMessage);        

        return response;
    }
    protected void IncommingMessageAsync(string requestInfo, byte[] message)
    {

       var obj =JObject.Parse(Convert.ToString(message)); 
    }    
    protected void OutgoingMessageAsync( string requestInfo, byte[] message)
    {

    }
}

请注明IncomingMessageAsync是否有

  var obj =JObject.Parse(Convert.ToString(message)); 

在解析错误的情况下会以详细模式引发异常

{
  "Message": "An error has occurred.",
  "ExceptionMessage": "Unexpected character encountered while parsing value: S. Path '', line 0, position 0.",
  "ExceptionType": "Newtonsoft.Json.JsonReaderException",
  "StackTrace": "   à Newtonsoft.Json.JsonTextReader.ParseValue()\r\n   à Newtonsoft.Json.JsonTextReader.Read()\r\n   à Newtonsoft.Json.Linq.JObject.Load(JsonReader reader)\r\n   à Newtonsoft.Json.Linq.JObject.Parse(String json)\r\n   à MessageHandler.IncommingMessageAsync(String requestInfo, Byte[] message) dans c:\\tests\\WebApplication2\\WebApplication2\\MessageHandler.cs:ligne 45\r\n   à MessageHandler.<SendAsync>d__0.MoveNext() dans c:\\tests\\WebApplication2\\WebApplication2\\MessageHandler.cs:ligne 21\r\n--- Fin de la trace de la pile à partir de l'emplacement précédent au niveau duquel l'exception a été levée ---\r\n   à System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)\r\n   à System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)\r\n   à System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()"
}

注意 出于安全原因从未这样做

改为创建自定义异常