Deserialize json with C# .NET Core

Michal Takáč picture Michal Takáč · Jan 3, 2018 · Viewed 15.3k times · Source

Im trying to deserialize data that Ive got over POST in JSON format but having some problem.

The error message is:

SerializationException: Expecting state 'Element'.. Encountered 'Text' with name '', namespace ''. System.Runtime.Serialization.XmlObjectSerializerReadContext.HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex)

Controller where the serialization is happening:

    public String RequestToken(string userData)
    {
            Contract.Ensures(Contract.Result<string>() != null);
            UserModel deserializedUser = new UserModel();
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(userData));
            ms.Position = 0;
            DataContractJsonSerializer ser = new DataContractJsonSerializer(deserializedUser.GetType());
            deserializedUser = ser.ReadObject(ms) as UserModel;
    }

UserModel that is used as a contract:

using System;
using System.Runtime.Serialization;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;

namespace WishareIntegrationApi.Entities
{
    [DataContract]
    public class UserModel
    {
        [BsonId]
        [BsonRepresentation(BsonType.String)]
        [DataMember]
        public ObjectId _id { get; set; }
        [DataMember]
        public string displayName { get; set; }
        [DataMember]
        public string photoURL { get; set; }
        [DataMember]
        public string email { get; set; }
        [DataMember]
        public int registeredAt { get; set; }
    }
}

And an example JSON i'm sending over post:

{"_id":"8kmXH1fzSrVS8PqNLMwyhRH4hBw1","displayName":"Michal Takáč","photoURL":"https://lh3.googleusercontent.com/-xa5oE48RffQ/AAAAAAAAAAI/AAAAAAAACDE/OLrtV5-VIvw/photo.jpg","email":"[email protected]"}

Answer

Michal Tak&#225;č picture Michal Takáč · Jan 3, 2018

Switch to JSON.Net.

JSON serialization APIs are not part of .Net core and I don't expect them to port that over. If you used classes from namespaces like System.Web.Script.Serialization switch to other serialization, in particular Microsfot frameworks based on .Net core use JSON.Net serializers.

As mentioned by many users in comments, I've switched from old way of doing serialization/deserialization using contracts to JSON.NET

Here is the correct solution for the controller

public async Task<String> RequestToken(string userData)
{
     var user = JsonConvert.DeserializeObject<UserModel>(userData);
}