Null Reference Exception in ServiceStack.Text

I am getting NullRef exception when calling below.

System.NullReferenceException occurred
Message: Exception thrown: ‘System.NullReferenceException’ in ServiceStack.Text.dll
Additional information: Object reference not set to an instance of an object.


That’s because it’s not valid JSON, which should look like:

var dto = "{\"X\":-3372,\"Y\":-12,\"Width\":3384,\"Height\":1844}".FromJson<Rectangle>();

Calling StringExtensions.ToJson(rect) created that JSON.

var r = new Rectangle(-3372, -12, 3384, 1844);




Is Rectangle a reference type? Otherwise struct’s are serialized in a scalar string value.

Also you shouldn’t call Dump on JSON which is already a string, you can just call:

dto.ToJson().Print();  // Equivalent to

Rectangle is struct from System.Drawing.

How can I serialize structs to proper json? Trying to switch from newtonsoft.

Here’s some info around serializing Struct values, i.e ServiceStack serializes a struct using their ToString() and tries to deserialize it with a single string constructor or a static Parse(string) function.

If it’s your own Struct you can customize deserialization by implementing a static ParseJson() method. If it can be treated as a reference type, i.e. only has public serializable properties you can tell ServiceStack to treat it as a reference type with:

JsConfig<Rectangle>.TreatValueAsRefType = true;

Otherwise you’ll need to customize the serialization by providing custom:

JsConfig<Rectangle>.SerializeFn = r => $$"{r.X},{r.Y},{r.Width},{r.Height}";
JsConfig<Rectangle>.DeSerializeFn = s => {
    var parts = s.Split(',');
    return new Rectangle(

Here’s an Live example you can run on Gistlyn.