3

I have the following code. With JSON.NET it works fine where I can deserialize the string into the CustomMaker object. With ServiceStack.Text I get null. I've tried doing { get; set; } and removing and adding the constructor.

With JSON.NET it simply worked like JsonConvert.DeserializeObject(xString);

Any idea why this does not work with ServiceStack.Text?

    static void Main(string[] args) {
        string xString = "{\"error\":\"Invalid token 1 #556264\"}";
        Console.WriteLine(xString);
        CustomMaker xSLBM = TypeSerializer.DeserializeFromString<CustomMaker>(xString);
        Console.WriteLine(string.IsNullOrWhiteSpace(xSLBM.error) ? "error is null" : xSLBM.error);
        Console.ReadLine();
    }

    [Serializable]
    public class CustomMaker {
        public int UserID;
        public String error;
        public CustomMaker() { }
    }

edit: This code also produces null:

    static void Main(string[] args) {
        JsConfig.IncludePublicFields = true;
        string xString = "{\"error\":\"Invalid token 1 #556264\"}";
        Console.WriteLine(xString);
        CustomMaker xSLBM = TypeSerializer.DeserializeFromString<CustomMaker>(xString);
        Console.WriteLine(string.IsNullOrWhiteSpace(xSLBM.error) ? "error is null" : xSLBM.error);
        Console.ReadLine();
    }

    [Serializable]
    public class CustomMaker {
        public CustomMaker() { }
        public int UserID { get; set; }
        public String error { get; set; }
    }

1 Answer 1

3

By Default ServiceStack only serializes public properties so you could refactor your DTO to include properties, e.g:

public class CustomMaker {
    public int UserID { get; set; }
    public String error { get; set; }
}

Or if you wanted to serialize public fields you can specify this with:

JsConfig.IncludePublicFields = true;

Also you need to use the JsonSerializer class, e.g:

CustomMaker xSLBM = JsonSerializer.DeserializeFromString<CustomMaker>(xString);

Or string.ToJson() or T.FromJson<T>(string) extension methods, e.g:

CustomMaker xSLBM = xString.FromJson<CustomMaker>();

The TypeSerializer class is only for serializing/deserializing the JSV Format, not JSON.

Sign up to request clarification or add additional context in comments.

3 Comments

I've already tried the property method, this code also produces null.
@CowKing see my update, you need to use the JsonSerializer class or ToJson/FromJson extension methods.
That did the trick, thanks! I guess the error was my fault in not understanding the difference between JSON and JSV.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.