Edit the JsonContentImporter
On the previous page we discussed the anatomy of a ContentImporter
. Now that we have an understanding of this, let's make the changes necessary to our JsonContentImporter
class so that it imports the contents of a JSON file.
Open the JsonContentImporter.cs
file and make the following adjustments:
using Microsoft.Xna.Framework.Content.Pipeline;
using System;
using System.IO;
using System.Text.Json;
using TImport = System.String;
namespace JsonContentPipelineExtension
{
[ContentImporter(".json", DisplayName = "Json Importer - Aristurtle", DefaultProcessor = nameof(JsonContentProcessor))]
public class JsonContentImporter : ContentImporter<TImport>
{
public override TImport Import(string filename, ContentImporterContext context)
{
// For importing JSON, we only need to import the content of the file as a string
string json = File.ReadAllText(filename);
ThrowIfInvalidJson(json);
return json;
}
private void ThrowIfInvalidJson(string json)
{
// Ensure there's actually data in the file.
if (string.IsNullOrEmpty(json))
{
throw new InvalidContentException("The JSON file is empty");
}
// Attempt to parse the data as a JsonDocument. If it fails, return false.
try
{
_ = JsonDocument.Parse(json);
}
catch(Exception ex)
{
throw new InvalidContentException("This does not appear to be valid JSON. See inner exception for details", ex);
}
}
}
}
These changes are pretty minimal but let's discuss what we're doing here.
- Additional
using
statements were added that we'll need for reading the file content. - The
ContentImporterAttribute
was updated- The
fileExtension
parameter was changed from.txt
to.json
since we will be importing JSON files specifically - The
DisplayName
property was changed toJSON Importer - Aristurtle
. This gives it a more descriptive name when displayed in the MGCB Editor. It is common practice to include either your name or the name of your library at the end of the display name as I have done here with- Aristurtle
. You can change this to your name if you'd like. - The
DefaultProcessor
was changed to be ourJsonContentProcessor
class. Here, in this example, I am making use of thenameof
keyword in C#, however you could hae just typed it as a string"JsonContentProcessor"
if you had wanted. The only thing that matters is that the name used for theDefaultProcessor
is a string and is the correct casing and spelling of the class.
- The
- The logic of the
Import(string, ContentImporterContext)
method was updated to read all of the text from the JSON file into thejson
variable, validate that it is actually JSON, then return it. The validation is done inside theThrowIfInvalidJson(string)
method that was added.
Next Steps
That's it for our JSON importer. Remember, the job of the ContentImporter
is to import the content of the file assets and perform any validation that the content imported is what is expected.
On the next page, we'll go over the anatomy of a ContentProcessor
class.