runtime icon indicating copy to clipboard operation
runtime copied to clipboard

System.Text.Json and case - different behavior in serialization and deserialization

Open tabinnorway opened this issue 7 years ago • 9 comments

If you have a class as such

public class MyClass {
  public string MyProperty { get;set; }
}

and a controller as such

public async Task<MyClass> MyController(...) {
   var myObj = await _db.GetSomeStuff();
   return myObj;
}

The object will be serialized as such

{
  myProperty: 'Some value'
}

So, on a client somewhere you do

MyClass myObj = System.Text.Json.JsonSerializer.Deserialize<MyClass>(jsonString);

It will not work, since the Deserialization method is case sensitive. This is in and off it self not a problem, but the two methods should agree on how to serialize and deserialize an object by default. In other words, if the default behavior of serialization is to change case, then the default behavior of deserialization should handle this.

I know the solution is to do

MyClass myObj = System.Text.Json.JsonSerializer.Deserialize<MyClass>(jsonString, new JsonSerializerOptions {
    PropertyNameCaseInsensitive = true,
    });

but the default behavior of the two operations should be compatible. Currently they are not.

tabinnorway avatar Sep 18 '19 15:09 tabinnorway

/cc @anurse @pranavkm Is MVC serializing with camelCase by default?

GrabYourPitchforks avatar Sep 18 '19 15:09 GrabYourPitchforks

Looks like it, yes. I believe that was it's previous behavior as well (when using Newtonsoft.Json), but this is a casualty of the fact that Newtonsoft.Json was case-insensitive by default whereas System.Text.Json is case-sensitive by default.

analogrelay avatar Sep 18 '19 16:09 analogrelay

You could consider changing MVC's default to use the default (Pascal casing) if you don't particularly care about the output format:

services.AddControllers().AddJsonOptions(options =>
{
    // Use the default property (Pascal) casing.
    options.SerializerOptions.PropertyNamingPolicy = null;
});

pranavkm avatar Sep 18 '19 16:09 pranavkm

System.Text.Json is case-sensitive by default.

Really? And MVC doesn't explicitly change this? I can't believe it's taken this long for a report like this if that's the case. Are people not roundtripping stuff from the server and back? 🤔

EDIT: Never mind, I'm an idiot.

khellang avatar Sep 18 '19 18:09 khellang

System.Text.Json does indeed use camlCase as default, so does Newtonsoft, now. Earlier Newtonsoft did not, and would (by default) use the same case as the POCO. A supplier of ours ran into this when upgrading their .Net server application, announcing they had changed nothing, and suddenly none of our Angular apps would work. JS is, as we know, case sensitive.

The "standard" for POCO is of course Pascal Case.

The difference betweenm System.Text.Json and Newtonsoft is that, to my knowledge, Newtonsoft handles camel case in both directions, even with Pascal Case POCOs.

I think it's a good thing that System.Text.Json serializes using camelCase. In the JS world that's the expected behavior. However, if it does, it should do so in reverse too, since POCOs are generally PascalCase. I am also not quite sure I like the solution of ignoring case, but that might be a bit insane on my part. I think the Deserializer should be able to convert from camelCase to PascalCase, but I don't think it should thereby accept any random case :-) As I said, I am a bit insane.

So, in my example at the top, the json should use camelCase. On deserialization it should parse

{
   myProperty: 'Hello'
}

correctly, but it should reject

{
   MYPROPERTY: 'Hello'
}

but, I might be borderline insane on that part.

tabinnorway avatar Sep 18 '19 19:09 tabinnorway

The default behavior of the S.T.Json serializer and deserializer are consistent and both emit/expect PascalCasing (outside of MVC).

What you are seeing here is the difference between the defaults ASP.NET MVC sets (serialize as camel case) and that being different from the default usage of the Deserializer on its own (pascal case).

@pranavkm gave some workarounds on the MVC side, and @tabinnorway, you have shared how to customize the deserialization itself. To me, this issue doesn't seem actionable given the behavior is by design. I don't think it makes sense to change the default serializer to be camel case and I don't know if we want the default deseralizer to be case-insensitive. Whenever we have anything less than an exact match, multiple properties would match the payload and then it becomes harder to reason about the result (as you observed, having MyProperty and myProperty match, but not MyProPeRTY highlights the problem).

Is there a particular reason the stated workarounds don't work for your scenario/use case?

cc @steveharter

ahsonkhan avatar Sep 20 '19 03:09 ahsonkhan

The default behavior of S.T.Json makes sense. As you said, it also makes sense that one should not, by default, use case insensitivity. I also see that when using MVC, the behavior is as expected, it will parse camelCase and populate an object that uses PascalCase with the appropriate values. So, if you have a controller similar to

[HttpPut("somestuff")]
public async Task<MyClass> UpdateSomeStuff( int id, [FromBody]MyClass myStuff) { ... }

then things will work. I think this is the correct behavior, and then if I need to encode or decode somewhere outside of the automagic encoding done by the MVC framework, then I need to be cognizant of this stuff, So it seems to work fine. I guess closing this is the correct thing to do.

tabinnorway avatar Sep 20 '19 13:09 tabinnorway

How to set PropertyNameCaseInsensitive globally?

yukozh avatar Apr 20 '20 13:04 yukozh

This wasted my 5 hours. Non of the document mentioned this.

AwsomeCode avatar Jun 15 '20 15:06 AwsomeCode