LitJSON / litjson

JSON library for the .Net framework
https://litjson.net/
Other
1.36k stars 403 forks source link

Serializing Guid type throws JsonException #127

Open srprash opened 3 years ago

srprash commented 3 years ago

Hi, Looking at this issue opened with our repo, I realized that LitJSON doesn't handle serializing Guid type very well and throws the following error:

Unhandled exception. LitJson.JsonException: Max allowed object depth reached while trying to export from type System.Guid
   at LitJson.JsonMapper.WriteValue(Object obj, JsonWriter writer, Boolean writer_is_private, Int32 depth) in C:\projects\litjson\src\LitJson\JsonMapper.cs:line 725
   at LitJson.JsonMapper.WriteValue(Object obj, JsonWriter writer, Boolean writer_is_private, Int32 depth) in C:\projects\litjson\src\LitJson\JsonMapper.cs:line 861
   at LitJson.JsonMapper.WriteValue(Object obj, JsonWriter writer, Boolean writer_is_private, Int32 depth) in C:\projects\litjson\src\LitJson\JsonMapper.cs:line 861
   at LitJson.JsonMapper.WriteValue(Object obj, JsonWriter writer, Boolean writer_is_private, Int32 depth) in C:\projects\litjson\src\LitJson\JsonMapper.cs:line 861

More details along with a repro code are on the issue. Let me know if there's a way to handle Guid without special casing. Would be happy to do a PR. Thanks!

kdprince commented 3 years ago

I believe the general case involves models that contain public properties that are recursive.

Here's a System.Runtime type that defines a recursive structure

public readonly struct DateTimeOffset 
{
  /// Recursive properties below
   public static DateTimeOffset UtcNow { get; }
   public static DateTimeOffset Now { get; }

}

Example:

 public class ModelWithSelfReferenceProp
  {
      public ModelWithSelfReferenceProp()
      {
          RightNow = DateTime.Now;
      }
      public DateTimeOffset RightNow { get; }
  }

  [Fact]
  public void TestShouldNotThrowError()
  {
      var model = new ModelWithSelfReferenceProp();

      JsonMapper.ToJson(model);
      Assert.NotNull(model);
  }

Max allowed object depth reached while trying to export from type System.DateTimeOffset