Json2CSharp / Json2CSharpCodeGenerator

Microsoft Reciprocal License
292 stars 81 forks source link

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

Open leonandroid opened 9 months ago

leonandroid commented 9 months ago

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 commented 1 month ago

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.