[英]ServiceStack.Text deserialize string into single object null reference
I have the following code. 我有以下代码。 With JSON.NET it works fine where I can deserialize the string into the CustomMaker object.
使用JSON.NET,它可以正常工作,我可以将字符串反序列化为CustomMaker对象。 With ServiceStack.Text I get null.
使用ServiceStack.Text,我得到null。 I've tried doing { get;
我试过做{get; set;
组; } and removing and adding the constructor.
并删除和添加构造函数。
With JSON.NET it simply worked like JsonConvert.DeserializeObject(xString); 使用JSON.NET,它就像JsonConvert.DeserializeObject(xString)一样工作;
Any idea why this does not work with ServiceStack.Text? 知道为什么这不适用于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: 编辑:此代码也产生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; }
}
By Default ServiceStack only serializes public properties so you could refactor your DTO to include properties, eg: 默认情况下,ServiceStack仅序列化公共属性,以便您可以重构DTO以包含属性,例如:
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, eg: 您还需要使用
JsonSerializer
类,例如:
CustomMaker xSLBM = JsonSerializer.DeserializeFromString<CustomMaker>(xString);
Or string.ToJson()
or T.FromJson<T>(string)
extension methods, eg: 或
string.ToJson()
或T.FromJson<T>(string)
扩展方法,例如:
CustomMaker xSLBM = xString.FromJson<CustomMaker>();
The TypeSerializer
class is only for serializing/deserializing the JSV Format , not JSON. TypeSerializer
类仅用于序列化/反序列化JSV格式 ,而不是JSON。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.