Search code examples
asp.net-mvcjsondatacontractserializer

How to deserialize JsonResult with DataContractJsonSerializer


i have an MVC Controller that returns:

public JsonResult ValidateUser(string siteId, string userName, string password) 
{
            UserObj userObj = new UserObj();
            userObj.Name = userName;
            return Json(JsonConvert.SerializeObject(userObj), JsonRequestBehavior.AllowGet);
}

Then in the client I have:

MemoryStream ms = new MemoryStream();
stream.Copy(ms);
var text = Encoding.Default.GetString(ms.ToArray());

They output text is: "{\"Name\":\"Peter\"}"

When trying to deserialize the value Name is null.

DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(UserObj));
var resultUser = obj.ReadObject(stream) as UserObj;

I found that the issue is in the backslashes.. any clue on how to make it work?

Thanks


Solution

  • Replace:

    return Json(JsonConvert.SerializeObject(userObj), JsonRequestBehavior.AllowGet);
    

    with:

    return Json(userObj, JsonRequestBehavior.AllowGet);