Reputation: 1750
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; }
}
Upvotes: 3
Views: 967
Reputation: 143319
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.
Upvotes: 3