简体   繁体   中英

Serialize list of complex objects to JSON

I can't figure out how to get Newtonsoft.Json to serialize this list:

var player = new List<ISprite>
    {
        new Sprite( head, position ),
        new Sprite( torso, position ),
        new Sprite( legs, position )
    };

fileParser.Write( "save.json", player );

The Sprite constructor takes two parameters: the first is the name of an asset and the second is a vector. FileParser.Write is defined as:

public void Write<T>( string fileName, T data )
{
    if ( string.IsNullOrEmpty( fileName ) )
    {
        throw new ArgumentNullException();
    }

    var json = JsonConvert.SerializeObject( data );

    File.WriteAllText( fileName, json );
}

The file is created, but the result is always an array of empty objects:

[{},{},{}]

What am I doing wrong here?

It seems that you don't have any public fields/properties in your Sprite class. A solution for this can be adding [JsonProperty] attribute to the private fields you want to serialize

In fact your code is fine, it should work properly. The thing is that maybe you are passing these Sprite instances empty to the json converter, are you assigning these values that you pass to constructor into the class properties, name and Vector? what type of values are "head", "legs", "torso" and position, are these strings or objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM