ReadObject DataContractJsonSerializer exception

I follow the accepted answer of ASP.NET MVC. How to pass a JSON object from a view to a controller as a parameter . Like the original question, I have a simple POCO.

Everthing works great for me before the DataContractJsonSerializer.ReadObject method. I get the following exception:

Waiting for the element 'root' from namespace '' .. Encountered 'None' with the name '', namespace ''.

 Public Overrides Sub OnActionExecuting(ByVal filterContext As ActionExecutingContext)
    If filterContext.HttpContext.Request.ContentType.Contains("application/json") Then
        Dim s As System.IO.Stream = filterContext.HttpContext.Request.InputStream

        Dim o = New DataContractJsonSerializer(RootType).ReadObject(s)

        filterContext.ActionParameters(Param) = o
    Else
        Dim xmlRoot = XElement.Load(New StreamReader(filterContext.HttpContext.Request.InputStream, filterContext.HttpContext.Request.ContentEncoding))
        Dim o As Object = New XmlSerializer(RootType).Deserialize(xmlRoot.CreateReader)
        filterContext.ActionParameters(Param) = o
    End If
End Sub

Any ideas?

+3
source share
2 answers

you may need to make sure that you apply an attribute [DataContract]and [DataMember]at its poco.

, mvc ControllerContext:

using System.Web;
using System.Web.Mvc;
using System.Web.Script.Serialization;

public static class MvcExtensions
{
    public static T DeserializeJson<T>(this ControllerContext context)
    {
        var serializer = new JavaScriptSerializer();
        var form = context.RequestContext.HttpContext.Request.Form.ToString();
        return serializer.Deserialize<T>(HttpUtility.UrlDecode(form));
    }
}

json JavaScriptSerializer :

var myInstance = controllerContext.DeserializeJson<MyClass>();

, , :

public class JsonBinder<T> : IModelBinder
{
    public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
    {
        return controllerContext.DeserializeJson<T>();
    }
}

mvc, poco:

[ModelBinder(typeof(JsonBinder<MyClass>))]
+7

, , - .

s.Position = 0
+4

Source: https://habr.com/ru/post/1740033/


All Articles