Skip to content

Commit

Permalink
#3584: Handle conversion of mixed NBT lists to json
Browse files Browse the repository at this point in the history
  • Loading branch information
md-5 committed Dec 22, 2023
1 parent b711e40 commit f5af111
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
20 changes: 18 additions & 2 deletions protocol/src/main/java/net/md_5/bungee/protocol/TagUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -124,9 +124,11 @@ public static SpecificTag fromJson(JsonElement json)
for ( JsonElement jsonEl : jsonArray )
{
SpecificTag subTag = fromJson( jsonEl );
if ( subTag.tagType() != listType )
if ( !( subTag instanceof CompoundTag ) )
{
throw new IllegalArgumentException( "Cannot convert mixed JsonArray to Tag" );
CompoundTag wrapper = new CompoundTag();
wrapper.add( "", subTag );
subTag = wrapper;
}

tagItems.add( subTag );
Expand Down Expand Up @@ -179,6 +181,20 @@ public static JsonElement toJson(SpecificTag tag)
JsonArray jsonList = new JsonArray( items.size() );
for ( SpecificTag subTag : items )
{
if ( subTag instanceof CompoundTag )
{
CompoundTag compound = (CompoundTag) subTag;
if ( compound.size() == 1 )
{
SpecificTag first = (SpecificTag) compound.get( "" );
if ( first != null )
{
jsonList.add( toJson( first ) );
continue;
}
}
}

jsonList.add( toJson( subTag ) );
}

Expand Down
29 changes: 29 additions & 0 deletions protocol/src/test/java/net/md_5/bungee/protocol/TagUtilTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package net.md_5.bungee.protocol;

import static org.junit.jupiter.api.Assertions.*;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import org.junit.jupiter.api.Test;
import se.llbit.nbt.SpecificTag;

public class TagUtilTest
{

private static final Gson GSON = new Gson();

private static void testDissembleReassemble(String json)
{
JsonElement parsedJson = GSON.fromJson( json, JsonElement.class );
SpecificTag nbt = TagUtil.fromJson( parsedJson );
JsonElement convertedElement = TagUtil.toJson( nbt );

String convertedJson = GSON.toJson( convertedElement );
assertEquals( json, convertedJson );
}

@Test
public void testStringLiteral()
{
testDissembleReassemble( "{\"text\":\"\",\"extra\":[\"hello\",{\"text\":\"there\",\"color\":\"#ff0000\"},{\"text\":\"friend\",\"font\":\"minecraft:default\"}]}" );
}
}

0 comments on commit f5af111

Please sign in to comment.