Skip to content

Commit

Permalink
Add methods to ComponentSerializer to parse styles, and test it
Browse files Browse the repository at this point in the history
  • Loading branch information
2008Choco committed Dec 12, 2023
1 parent 2fe9d2b commit 2035f8f
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
38 changes: 38 additions & 0 deletions chat/src/main/java/net/md_5/bungee/chat/ComponentSerializer.java
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,44 @@ public static BaseComponent deserialize(JsonElement jsonElement)
return gson.fromJson( jsonElement, BaseComponent.class );
}

/**
* Deserialize a JSON-compliant String as a component style.
*
* @param json the component style json to parse
* @return the deserialized component style
* @throws IllegalArgumentException if anything other than a valid JSON
* component style string is passed as input
*/
public static ComponentStyle deserializeStyle(String json)
{
JsonElement jsonElement = JsonParser.parseString( json );

return deserializeStyle( jsonElement );
}

/**
* Deserialize a JSON element as a component style.
*
* @param jsonElement the component style json to parse
* @return the deserialized component style
* @throws IllegalArgumentException if anything other than a valid JSON
* component style is passed as input
*/
public static ComponentStyle deserializeStyle(JsonElement jsonElement)
{
return gson.fromJson( jsonElement, ComponentStyle.class );
}

public static JsonElement toJson(BaseComponent component)
{
return gson.toJsonTree( component );
}

public static JsonElement toJson(ComponentStyle style)
{
return gson.toJsonTree( style );
}

public static String toString(Object object)
{
return gson.toJson( object );
Expand All @@ -146,6 +179,11 @@ public static String toString(BaseComponent... components)
}
}

public static String toString(ComponentStyle style)
{
return gson.toJson( style );
}

@Override
public BaseComponent deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException
{
Expand Down
10 changes: 10 additions & 0 deletions chat/src/test/java/net/md_5/bungee/api/chat/ComponentsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,16 @@ public void testScore()
assertArrayEquals( component, reparsed );
}

@Test
public void testStyle()
{
ComponentStyle style = ComponentSerializer.deserializeStyle( "{\"color\":\"red\",\"font\":\"minecraft:example\",\"bold\":true,\"italic\":false,\"obfuscated\":true}" );
String text = ComponentSerializer.toString( style );
ComponentStyle reparsed = ComponentSerializer.deserializeStyle( text );

assertEquals( style, reparsed );
}

@Test
public void testBuilderAppendCreate()
{
Expand Down

0 comments on commit 2035f8f

Please sign in to comment.