Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why JsonConvert.DeserializeObject ignoring JsonPropertyName attributes?

I have problem with JsonConvert deserializer. I have class

[BsonCollection("matches")]
public class MatchData : Document
{
    [JsonPropertyName("id")]
    public string ExternalMatchId { get; set; }

    ...
}    

In my controller, I am trying to deserialize in this way:

[HttpPost("end")]
public ActionResult RoundEnd([FromBody] dynamic data)
{
    var saveData = JsonConvert.DeserializeObject<MatchData>(data.ToString());

    ...
}

Input JSON looks like

 "{"id": "61696f268c7b70b5f3e85803",
 "game_server_id": "615ed4a1cd95e8209a4ab67d",
...

But in my output MatchData object ExternalMatchId is null. How to fix that?

like image 794
hoozr Avatar asked Oct 23 '25 19:10

hoozr


1 Answers

You are mixing frameworks here. The JsonPropertyName attribute is for the System.Text.Json namespace whereas you are using JSON.Net to deserialise. So the solution is to stick with one of them. Either deserialise with the built in framework:

System.Text.Json.JsonSerializer.Deserialize<MatchData>(data.ToString());

Or switch the attributes to use the JSON.Net versions:

[JsonProperty("Foo")]

Having said all that, it looks like you can simplify the whole thing by getting MVC to do the work for you. Instead of using dynamic as the model (don't do that - dynamic is problematic and every time you use it a kitten dies), put the model in here directly:

public ActionResult RoundEnd([FromBody] MatchData data)
like image 112
DavidG Avatar answered Oct 26 '25 09:10

DavidG