Modding:Modder Guide/APIs/Data

From Stardew Valley Wiki
< Modding:Modder Guide‎ | APIs
Revision as of 19:47, 18 August 2018 by Pathoschild (talk | contribs) (create page (rewritten from content in Modding:Modder Guide/APIs/Config; only author for the affected content is Pathoschild))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Creating SMAPI mods SMAPI mascot.png


Modding:Index

The data API lets you store arbitrary data and retrieve it later. For example, you can use this to store player progression, custom items that can't be saved by the game, etc. The data is stored in JSON files in your mod folder.

Data model

Creating a data model

The data model is a C# class you create, with properties representing the data you want to store. It can contain almost anything from a few boolean fields to a complex object graph. Here's a simple data model:

class ModData
{
   public bool ExampleBoolean { get; set; }
   public float ExampleFloat { get; set; }
}

If you save that model to a JSON file, the file would look like this:

{
   "ExampleBoolean": false,
   "ExampleFloat": 0
}

Default values

You can optionally set default values in your data model:

class ModData
{
   public bool ExampleBoolean { get; set; } = true;
   public float ExampleFloat { get; set; } = 0.5f;
}

...or set defaults with a constructor:

class ModData
{
   public bool ExampleBoolean { get; set; }
   public float ExampleFloat { get; set; }

   public ModData()
   {
      this.ExampleBoolean = true;
      this.ExampleFloat = 0.5f;
   }
}

Storage options

JSON files

You can store data in arbitrary .json files in your mod folder (SMAPI will automatically parse and normalise them):

  1. Create your data model.
  2. In your mod code, use the mod helper to read/write a named file. This example assumes you created a class named ModData, but you can use different names too.
    // read file
    var model = this.Helper.ReadJsonFile<ModData>("data.json") ?? new ModData();
    
    // save file (if needed)
    this.Helper.WriteJsonFile("data.json", model);
    
    Note that ReadJsonFile will return null if the file doesn't exist. The above example will create a default instance if that happens; if you don't want to do that, just remove the ?? new ModData() part.

By changing the file path you specify, you can...

  • store JSON files in a subfolder, by specifying a path relative to your mod folder (like "data/some-file.json"). SMAPI will create the folders automatically if needed.
  • create per-save JSON files by using the save ID in the name, like $"data/{Constants.SaveFolderName}.json".