Tomek Kopek
Tomek Kopek

Reputation: 31

C# JsonConverter unable to deserialize object from JsonResult

I have an API method witch returns model as json using my helper method

public static JsonResult ParseObjectToJsonResult<T>(T objectToParse) where T : class
{
    return new JsonResult(JsonConvert.SerializeObject(objectToParse));
}

Then on the mobile side I am trying to deserialize this Json to the same model (simplified):

return JsonConvert.DeserializeObject<T>([string with response]);

Unfortunately I am getting an error and I am not sure why...

Newtonsoft.Json.JsonSerializationException: Error converting value "{"UserId":"00f0299f-3210-45bb-ab6f-5995de30bf26","IsSuccess":true,"Message":""}" to type 'Models.APIResponseModels.LoginResponseModel'. Path '', line 1, position 91.

My model looks like :

JsonProperty(PropertyName = "UserId")]
        public string UserId { get; set; }

        [JsonProperty(PropertyName = "IsSuccess")]
        public bool IsSuccess { get; set; }

        [JsonProperty(PropertyName = "Message")]
        public string Message { get; set; }

Any ideas?

Upvotes: 1

Views: 106

Answers (1)

user47589
user47589

Reputation:

Change:

return new JsonResult(JsonConvert.SerializeObject(objectToParse));

to

return new JsonResult(objectToParse);

You're double-serializing your data. JsonConvert serializes it to a string, then JsonResult takes that string and serializes it again.

(Also, rename objectToParse to something else. It isn't being parsed. Parsing is the set of steps to turn a string into some kind of data structure. You're going the other direction - a data structure to a string.)

Upvotes: 8

Related Questions