Big McLargeHuge
Big McLargeHuge

Reputation: 16056

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?

Upvotes: 1

Views: 993

Answers (2)

en-user
en-user

Reputation: 21

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.

Upvotes: 0

L.B
L.B

Reputation: 116168

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

Upvotes: 2

Related Questions