ServiceStack.Text json deserialization creates wrong object instead of throwing on invalid json input string
This is resolved in ServiceStack.Text v4+ which by default doesn't populate incomplete collections, e.g:
public class Poco{ public string ExtId { get; set; } public string Name { get; set; } public string[] Mobiles { get; set; }}var json = "[{\"ExtId\":\"2\",\"Name\":\"VIP sj�lland\",\"Mobiles\":[\"4533333333\",\"4544444444\"]";var dto = json.FromJson<Poco[]>();Assert.That(dto[0].ExtId, Is.EqualTo("2"));Assert.That(dto[0].Name, Is.EqualTo("VIP sj�lland"));Assert.That(dto[0].Mobiles, Is.Null);
Or if preferred can throw on Error:
JsConfig.ThrowOnDeserializationError = true;Assert.Throws<SerializationException>(() => json.FromJson<Poco[]>());
C# is a little bit picky when it comes to JSON. Following would be valid! Note i do not have anonymous object array as the default element.
{ "ExtItem": [ { "ExtId": "2", "Name": "VIPsj�lland", "Mobiles": [ "4533333333", "4544444444" ] } ]}
If i generate a POCO from this I get
public class Rootobject{ public Extitem[] ExtItem { get; set; }}public class Extitem{ public string ExtId { get; set; } public string Name { get; set; } public string[] Mobiles { get; set; }}
I personally use extension method to string
public static class Extensions{ public static bool DeserializeJson<T>(this String str, out T item) { item = default(T); try { item = new JavaScriptSerializer().Deserialize<T>(str); return true; } catch (Exception ex) { return false; } }}
This would enable me to write:
Rootobject ext;const string validJson = @"{ ""ExtItem"": [ { ""ExtId"":""2"", ""Name"":""VIPsj�lland"", ""Mobiles"":[ ""4533333333"", ""4544444444"" ] } ]}";if (validJson.DeserializeJson(out ext)){ //valid input // following would print 2 elements : 4533333333, 4544444444 Console.WriteLine(string.Join(", ", ext.ExtItem.First().Mobiles)); } //invalid input
I tried this an have the exception thrown when I missed the } at the end.
In C#, the format for JSON is {"name", "value"} not [{"name", "value"}].
class M { public string ExtId { get; set; } public string Name { get; set; } public List<string> Mobiles { get; set; } }string str = "{\"ExtId\":\"2\",\"Name\":\"VIP\",\"Mobiles\":[\"4533333333\",\"4544444444\"]";M m = JsonConvert.DeserializeObject<M>(str);
When run this, you will get error as a } is missing.
Using:
string str = "{\"ExtId\":\"2\",\"Name\":\"VIP\",\"Mobiles\":[\"4533333333\",\"4544444444\"]}";
The object is deserialized fine.
You can see the JSON of this object from:
string s = JsonConvert.SerializeObject(m);