Create a Text Component
In this tutorial, you will learn how to create a simple plain-text component, and serialize it to JSON.
Note
This tutorial is written for MineJason version 0.4.0. APIs may have changed after that.
Prerequisites
- Entry to intermediate C# programming experience.
- .NET SDK version 8 or later, with your favourite code editor or IDE.
In this tutorial, we will use the .NET CLI to create the project, and add MineJason package.
Creating the project
- Create a directory in anywhere that you can remember.
- Navigate to the directory, and open your terminal in that directory. Alternatively, you can open your terminal at anywhere else and navigate through the shell to the directory you just created.
- Run the following commands:
dotnet new sln --name "Tutorial"
dotnet new console --name "Tutorial"
dotnet sln add "Tutorial.csproj"
These commands will create a solution and a project, both named Tutorial, and add the project to the solution.
Referencing MineJason
Now we must add the MineJason package to your project. Again, open your terminal in the directory you created, and enter:
dotnet add package MineJason --prerelease
This will add the latest version of MineJason to your project.
Creating a Chat Component
Open Program.cs
in your favourite editor. If everything succeeds, it should look like this:
Console.WriteLine("Hello World!");
First, lets add imports. Add these lines to the beginning of the file:
using MineJason;
Let's first create your first component. Add this before the Console.WriteLine
call:
var component = ChatComponent.CreateText("Hello World!");
Now you've created a chat component with no colors, no text decorations, no click and hover events, and only have text of "Hello World!"
.
Serializing chat components
Now you can serialize the component to JSON. Add this line after the line of code creating the component:
var json = JsonSerializer.Serialize(component);
If nothing goes wrong, your code should now look like this:
using MineJason;
using System.Text.Json;
var component = ChatComponent.CreateText("Hello World!");
var json = JsonSerializer.Serialize(component);
Console.WriteLine("Hello World!");
Now, you can modify the last line to this:
Console.WriteLine(json);
Run the project
Go back to your terminal, and type:
dotnet run
And if nothing goes wrong, it will display:
{"text":"Hello World!"}