我有以下代码.使用JSON.NET可以正常工作,在这里我可以将字符串反序列化到CustomMaker对象中.使用ServiceStack.Text我得到null.我尝试做{组;并删除并添加构造函数.
使用JSON.NET,它就像JsonConvert.DeserializeObject(xString);一样工作.
知道为什么这不适用于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() { }
}
编辑:此代码还产生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; }
}
解决方法:
默认情况下,ServiceStack仅序列化公共属性,因此您可以重构DTO以包括属性,例如:
public class CustomMaker {
public int UserID { get; set; }
public String error { get; set; }
}
或者,如果您要序列化公共字段,则可以使用以下命令进行指定:
JsConfig.IncludePublicFields = true;
您还需要使用JsonSerializer类,例如:
CustomMaker xSLBM = JsonSerializer.DeserializeFromString<CustomMaker>(xString);
或string.ToJson()或T.FromJsonT(string)扩展方法,例如:
CustomMaker xSLBM = xString.FromJson<CustomMaker>();
TypeSerializer类仅用于序列化/反序列化JSV Format,而不用于JSON.