Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Opt-out of JTokenType.Guid (and other "custom" JTokenTypes) #2948

Open
mvarendorff opened this issue Apr 29, 2024 · 0 comments
Open

Opt-out of JTokenType.Guid (and other "custom" JTokenTypes) #2948

mvarendorff opened this issue Apr 29, 2024 · 0 comments

Comments

@mvarendorff
Copy link

Source/destination types

public record Example(Guid Id);

Source/destination JSON

{ "Id": "e4729b1e-3f1f-4386-b5c7-2a828280f8f0" }

Expected behavior

JObject.FromObject(x) acts as a "shortcut" to JObject.Parse(JsonConvert.SerializeObject(x)). If it doesn't act like such a shortcut by default, a flag could be passed to the serializer for JObject.FromObject to enable behaviour that makes it a shortcut to serializing to string, then parsing again.

Actual behavior

JObject.FromObject embeds additional metadata into the values, like JTokenType.Guid, JTokenType.Date, etc. This creates a difference in behaviour between JObject.FromObject and using JObject.Parse on a previously serialized version of the same object. This is very frustrating when having to write code that has to deal with JObject instances from both sources.

Steps to reproduce

public record Example(Guid Id);

public class Program {
    public static void Main(string[] args) {
        var example = new Example(Guid.NewGuid());

        // Convert to string and parse that
        var exampleJsonFromParsedString = JObject.Parse(JsonConvert.SerializeObject(example));
        var exampleIdFromParsedString = exampleJsonFromParsedString.Value<string>("Id");
        Console.Out.WriteLine("exampleIdFromParsedString = {0}", exampleIdFromParsedString);

        // Convert to JObject directly
        var exampleJsonFromObject = JObject.FromObject(example);
        var exampleIdFromObject = exampleJsonFromObject.Value<string>("Id");
        Console.Out.WriteLine("exampleIdFromObject = {0}", exampleIdFromObject);
    }
}

Related: #1449 (note, I am not saying those JTokenTypes should be removed, I am just asking for a way to opt-out of them when serializing directly to JObject).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant