0

Here is code:

using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    private void Start()
    {
        var a = new A
        {
            array = new int[] { 1, 2, 3 }
        };

        print(JsonConvert.SerializeObject(a));
    }
}

/*
 * 
 * Uncomment the comments in <struct A> will cause Infite loop (Unity3D will be hanged)! Why ?
 *
*/

[Serializable]
public struct A /*: IEnumerable<int>*/
{
    public int[] array;


    //public IEnumerator<int> GetEnumerator()
    //{
    //  while (true) foreach (int i in array) yield return i;
    //}


    //IEnumerator IEnumerable.GetEnumerator()
    //{
    //  while (true) foreach (int i in array) yield return i;
    //}
}

If I uncomment the comments in structure A, it will cause Untiy3D hanged forever. I don't know about the workflow of JSON.NET. I don't know why JsonConvert called the method GetEnumerator? I think it should not call. Please help me to understand, Thank you so much

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • 1
    You have an infinite loop in `GetEnumerator()`. `while (true)` causes it to never end. You need to get rid of the `while(true)` as shown here: https://dotnetfiddle.net/Rvh6eP – dbc Nov 27 '19 at 06:45
  • But why did JSON.NET call the method "GetEnumerator" ? I use "while (true)" for my purpose. – Nguyễn Thanh Tâm Nov 27 '19 at 06:50
  • 1
    Because JSON.NET thinks it's a custom list type, presumably. – ProgrammingLlama Nov 27 '19 at 06:54
  • ok thank you very much ! i now understand a little. – Nguyễn Thanh Tâm Nov 27 '19 at 06:58
  • 1
    From https://www.newtonsoft.com/json/help/html/SerializationGuide.htm#Lists: *.NET lists (types that inherit from IEnumerable) and .NET arrays are converted to JSON arrays.* Since your type implements `IEnumerable`, as documented Json.NET iterate through the items and serializes them to JSON as array elements which requires a call to `GetEnumerator()`. – dbc Nov 27 '19 at 07:41
  • 1
    If you want to serialize your collections properties rather than items, mark it with `[JsonObject]` as shown in [this answer](https://stackoverflow.com/a/39173668/3744182) to [How to serialize/deserialize a custom collection with additional properties using Json.Net](https://stackoverflow.com/q/14383736/3744182). – dbc Nov 27 '19 at 07:45

0 Answers0