ServiceStack / Issues

Issue Tracker for the commercial versions of ServiceStack
11 stars 8 forks source link

Bug in TypeSerializer when Serialize and Deserialize NameValueCollection #800

Closed vzsoft closed 10 months ago

vzsoft commented 10 months ago

Describe the issue

Hi, I got error in TypeSerializer when Deserialize type NameValueCollection and Serialize not correct

Reproduction

code in C#:

            var nvc = new NameValueCollection();
            nvc.Add("A", "Test1");
            nvc.Add("B", "Test2");
            var text = TypeSerializer.SerializeToString(nvc); //result not correct 
            var deserialize = TypeSerializer.DeserializeFromString<NameValueCollection>(text); //Error

Expected behavior

correct result in SerializeToString {A:Test1,B:Test2}

System Info

Windows 10
ServiceStack.Text 6.11

Additional context

sry my english not good

Validations

mythz commented 10 months ago

NameValueCollection is not a serializable class, but you can convert it to an Object Dictionary and serialize that:

var text = TypeSerializer.SerializeToString(nvc.ToObjectDictionary()); 
var deserialize = TypeSerializer.DeserializeFromString<Dictionary<string,object>>(text); 

Although when dealing with adhoc or unstructured types like Dictionary<string,object> we recommend using the JSON Utils in ServiceStack.Common instead, e.g:

var json = JSON.stringify(nvc.ToObjectDictionary());
var fromJson = JSON.parse(json);
fromJson.PrintDump();

The ServiceStack.Text is better suited for de/serializing from known Types.