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

Json to C# does not suggest the GUID type properly. #107

Open
leonandroid opened this issue Sep 10, 2023 · 1 comment
Open

Json to C# does not suggest the GUID type properly. #107

leonandroid opened this issue Sep 10, 2023 · 1 comment

Comments

@leonandroid
Copy link

Hello.

The case is simple, this json:

{
            "matchId": "08b10c61-3e04-475a-878e-606c3615d2f3",
            "gameStartTime": 1594859132913,
            "teamId": "Red"
}

Expected is the MatchId as GUID, but is actually adding it as a String.
Would not cause an error, but would be nice if a string could be checked first if it's a valid GUID, before assigning it as string.


    public class Root
    {
        public string MatchId { get; set; }
        public long GameStartTime { get; set; }
        public string TeamId { get; set; }
    }
@Moamen189
Copy link

To ensure that the MatchId property is assigned as a GUID if it's a valid GUID string and as a string otherwise, you can modify the MatchId property in your Root class to handle this logic. Here's how you can do it:

using System;

public class Root
{
    private string _matchId;

    public string MatchId
    {
        get => _matchId;
        set
        {
            // Check if the value is a valid GUID
            if (Guid.TryParse(value, out Guid guidValue))
            {
                // If it's a valid GUID, assign it as a GUID
                _matchId = guidValue.ToString();
            }
            else
            {
                // Otherwise, assign it as a string
                _matchId = value;
            }
        }
    }

    public long GameStartTime { get; set; }
    public string TeamId { get; set; }
}

In this modified version of the Root class, the MatchId property has a custom setter that checks if the value is a valid GUID using Guid.TryParse(). If it's a valid GUID, it assigns it as a string representation of the GUID (guidValue.ToString()), otherwise, it assigns it as a regular string. This ensures that the MatchId property is assigned correctly based on whether the value is a valid GUID or not.

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

2 participants