@@ -249,6 +249,26 @@ fn test_serialize_same_table_twice() -> LuaResult<()> {
249249 Ok ( ( ) )
250250}
251251
252+ #[ test]
253+ fn test_serialize_empty_table ( ) -> LuaResult < ( ) > {
254+ let lua = Lua :: new ( ) ;
255+
256+ let table = Value :: Table ( lua. create_table ( ) ?) ;
257+ let json = serde_json:: to_string ( & table. to_serializable ( ) ) . unwrap ( ) ;
258+ assert_eq ! ( json, "{}" ) ;
259+
260+ // Set the option to encode empty tables as array
261+ let json = serde_json:: to_string ( & table. to_serializable ( ) . encode_empty_tables_as_array ( true ) ) . unwrap ( ) ;
262+ assert_eq ! ( json, "[]" ) ;
263+
264+ // Check hashmap table with this option
265+ table. as_table ( ) . unwrap ( ) . set ( "hello" , "world" ) ?;
266+ let json = serde_json:: to_string ( & table. to_serializable ( ) . encode_empty_tables_as_array ( true ) ) . unwrap ( ) ;
267+ assert_eq ! ( json, r#"{"hello":"world"}"# ) ;
268+
269+ Ok ( ( ) )
270+ }
271+
252272#[ test]
253273fn test_to_value_struct ( ) -> LuaResult < ( ) > {
254274 let lua = Lua :: new ( ) ;
@@ -667,6 +687,37 @@ fn test_from_value_userdata() -> Result<(), Box<dyn StdError>> {
667687 Ok ( ( ) )
668688}
669689
690+ #[ test]
691+ fn test_from_value_empty_table ( ) -> Result < ( ) , Box < dyn StdError > > {
692+ let lua = Lua :: new ( ) ;
693+
694+ // By default we encode empty tables as objects
695+ let t = lua. create_table ( ) ?;
696+ let got = lua. from_value :: < serde_json:: Value > ( Value :: Table ( t. clone ( ) ) ) ?;
697+ assert_eq ! ( got, serde_json:: json!( { } ) ) ;
698+
699+ // Set the option to encode empty tables as array
700+ let got = lua
701+ . from_value_with :: < serde_json:: Value > (
702+ Value :: Table ( t. clone ( ) ) ,
703+ DeserializeOptions :: new ( ) . encode_empty_tables_as_array ( true ) ,
704+ )
705+ . unwrap ( ) ;
706+ assert_eq ! ( got, serde_json:: json!( [ ] ) ) ;
707+
708+ // Check hashmap table with this option
709+ t. raw_set ( "hello" , "world" ) ?;
710+ let got = lua
711+ . from_value_with :: < serde_json:: Value > (
712+ Value :: Table ( t) ,
713+ DeserializeOptions :: new ( ) . encode_empty_tables_as_array ( true ) ,
714+ )
715+ . unwrap ( ) ;
716+ assert_eq ! ( got, serde_json:: json!( { "hello" : "world" } ) ) ;
717+
718+ Ok ( ( ) )
719+ }
720+
670721#[ test]
671722fn test_from_value_sorted ( ) -> Result < ( ) , Box < dyn StdError > > {
672723 let lua = Lua :: new ( ) ;
0 commit comments