Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialize json with C# .NET Core

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]"}
like image 266
Michal Takáč Avatar asked Jan 03 '18 10:01

Michal Takáč


People also ask

How do I deserialize JSON data?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

How JSON deserialization works in C#?

In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data. It returns a custom object (BlogSites) from JSON data.

What is JSON deserialization?

Deserialization is the process of reversing a String from a previously serialized format. This coverts the serialized String into a format that allows its Data Structure properties to be accessible to manipulation.

Does C have JSON?

JSON-C implements a reference counting object model that allows you to easily construct JSON objects in C, output them as JSON formatted strings and parse JSON formatted strings back into the C representation of JSON objects. It aims to conform to RFC 7159.


1 Answers

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);
}
like image 79
Michal Takáč Avatar answered Sep 21 '22 13:09

Michal Takáč