Home > Enterprise >  Unity JSONUtility to JSON list of base classes
Unity JSONUtility to JSON list of base classes

Time:04-15

I have a BaseClass and bunch of derived classes.

I also have List<BaseClass> that contains objects from those derived classes.

When I do JSONUtility.ToJson(List<BaseClass>) I get only properties of BaseClass and not derived classes.

And well... I guess it is logical, but can't I force it to use derived class if there's a one or JSONUtility isn't capable of it? So I need to write custom logic for that?

Thanks!

CodePudding user response:

Very probably JSONUtility.ToJson(List<BaseClass>) gets the elements you need with reflection, so the object returned is based on the incoming type. I would try to obtain the jsons one by one and combine them in the logic, pre casting each of the types. Not tested nor debugged, just an starting point idea to move on:

string jsons;
foreach (var baseClass in baseClassList) {
    Type specificType = baseClass.GetType();
    string jsonString =  JsonUtility.ToJson((specificType)baseClass)
    jsons = "["   string.Join(",", jsonstring)   "]";
}

CodePudding user response:

I faced the same issue, to be honest JsonUtility is not good option for working with List.

My recommendations:

  1. Use array instead of list with this helper class
  2. or Newtonsoft Json Unity Package

CodePudding user response:

I also needed JSON serialization, to call a REST json API, and I suggest to avoid JSONUtility.

It doesn't handle lists or dictionaries, as you saw.

Also it cannot serialize properties defined with { get; set; }, only fields, which is not blocking but not very convenient.

I agree with the recommendation above, just use Newtonsoft. It can serialize anything, and you will also benefit of the Serialization Settings (you can for example setup the contract resolver to convert all property names to snake_case...). See https://www.newtonsoft.com/json/help/html/SerializationSettings.htm

  • Related