How can I convert Component to String?

sponge 8.0

Component msg = Component.text(“§a§lHello!”);

String componentToString = ???

How can I convert Component to String ?

please help me.

A few ways depending on what you want.

There is plain which will extract just the text and nothing else. So formatting, colours, etc will be lost

PlainTextComponentSerializer.plainText()

https://docs.advntr.dev/serializer/plain.html

There is legacy, which extracts out the text as well as the legacy magic values (your example uses this). This may loose some colour and formattings, but if its user input then most users prefer this to the gson option (below).

You can change the special character to something else as most users dont have § on their keyboard (typically changed to &)

LegacyComponentSerializer.legacySection()

https://docs.advntr.dev/serializer/legacy.html

Last option supported by sponge is GSON. Which is what you should be using if loading/saving (i personally offer it as a user input too as well as legacy). It is lossless so no formatting or colour is lost but it can be a pain to some users, especially if they arnt being helped by suggestions

GsonComponentSerializer.gson()

https://docs.advntr.dev/serializer/gson.html

1 Like

Thank, but How can I get the string that still contains § ?

(I don’t want it to format to &)

Use legacy with the legacySection call. There is a method in there to change it to whatever you want if that doesnt work