diff --git a/SteamKit2/SteamKit2/Types/KeyValue.cs b/SteamKit2/SteamKit2/Types/KeyValue.cs index 676718936..9c977d50c 100644 --- a/SteamKit2/SteamKit2/Types/KeyValue.cs +++ b/SteamKit2/SteamKit2/Types/KeyValue.cs @@ -733,7 +733,7 @@ void RecursiveSaveBinaryToStreamCore( Stream f ) // Only supported types ATM: // 1. KeyValue with children (no value itself) // 2. String KeyValue - if ( Children.Any() ) + if ( Value == null ) { f.WriteByte( ( byte )Type.None ); f.WriteNullTermString( GetNameForSerialization(), Encoding.UTF8 ); @@ -747,7 +747,7 @@ void RecursiveSaveBinaryToStreamCore( Stream f ) { f.WriteByte( ( byte )Type.String ); f.WriteNullTermString( GetNameForSerialization(), Encoding.UTF8 ); - f.WriteNullTermString( Value ?? string.Empty, Encoding.UTF8 ); + f.WriteNullTermString( Value, Encoding.UTF8 ); } } diff --git a/SteamKit2/Tests/KeyValueFacts.cs b/SteamKit2/Tests/KeyValueFacts.cs index 17b243576..56b5545c2 100644 --- a/SteamKit2/Tests/KeyValueFacts.cs +++ b/SteamKit2/Tests/KeyValueFacts.cs @@ -478,6 +478,55 @@ public void KeyValuesEscapesTextWhenSerializing() Assert.Equal( expectedValue, text ); } + [Fact] + public void KeyValuesTextPreserveEmptyObjects() + { + var kv = new KeyValue( "key" ); + kv.Children.Add( new KeyValue( "emptyObj" ) ); + kv.Children.Add( new KeyValue( "emptyString", string.Empty ) ); + + string text; + using ( var ms = new MemoryStream() ) + { + kv.SaveToStream( ms, asBinary: false ); + ms.Seek( 0, SeekOrigin.Begin ); + using ( var reader = new StreamReader( ms ) ) + { + text = reader.ReadToEnd(); + } + } + + var expectedValue = "\"key\"\n{\n\t\"emptyObj\"\n\t{\n\t}\n\t\"emptyString\"\t\t\"\"\n}\n"; + Assert.Equal( expectedValue, text ); + } + + [Fact] + public void KeyValuesBinaryPreserveEmptyObjects() + { + var expectedHexString = "006B65790000656D7074794F626A000801656D707479537472696E6700000808"; + + var kv = new KeyValue( "key" ); + kv.Children.Add( new KeyValue( "emptyObj" ) ); + kv.Children.Add( new KeyValue( "emptyString", string.Empty ) ); + + var deserializedKv = new KeyValue(); + byte[] binaryValue; + using ( var ms = new MemoryStream() ) + { + kv.SaveToStream( ms, asBinary: true ); + ms.Seek( 0, SeekOrigin.Begin ); + binaryValue = ms.ToArray(); + deserializedKv.TryReadAsBinary( ms ); + } + + var hexValue = BitConverter.ToString( binaryValue ).Replace( "-", "" ); + + Assert.Equal( expectedHexString, hexValue ); + Assert.Null( deserializedKv["emptyObj"].Value ); + Assert.Empty( deserializedKv["emptyObj"].Children ); + Assert.Equal( string.Empty, deserializedKv["emptyString"].Value ); + } + [Fact] public void DecodesBinaryWithFieldType10() {