使用 Newtonsoft.Json 进行枚举反序列化
Enum deserialization with Newtonsoft.Json
你好,我想反序列化一个 class 并且在这个 class 中是一个枚举值:
[JsonConverter(typeof(StringEnumConverter))]
public enum MessageType {
Verify,
Disconnect,
}
[Serializable]
public class SocketMessage {
public Dictionary<String, String> Header { get; private set; }
public MessageType MessageType { get; private set; }
public SocketMessage(MessageType type) {
Header = new Dictionary<String, String>();
MessageType = type;
}
public void AddHeaderData(String key, String data) {
Header.Add(key, data);
}
public byte[] ToJSONBytes() {
String json = JsonConvert.SerializeObject(this);
return Encoding.UTF8.GetBytes(json);
}
public static SocketMessage FromJSONBytes(byte[] json) {
String s = Encoding.UTF8.GetString(json);
return JsonConvert.DeserializeObject<SocketMessage>(s);
}
}
字典将被正确反序列化,但枚举总是得到他的默认值>验证< json 看起来像这样:{"Header":{"Test":"Test"},"MessageType" :"断开连接"}
我真的不明白为什么会这样
感谢任何帮助!
由于 MessageType
属性 上的 private set
,它无法正常工作。所以 getter
是 public 所以它序列化很好,但是当涉及到反序列化时,它被忽略了。对此有一些可能的解决方案。
- 对
MessageType
使用 public setter。不过,您首先想要使用私有 setter 可能是有原因的,所以这可能不适合您。
- 将
JsonProperty
属性应用于 MessageType
属性:
[JsonProperty]
public MessageType MessageType { get; private set; }
- 将构造函数参数名称更改为
messageType
而不是type
,因此它与序列化名称匹配:
public SocketMessage(MessageType messageType)
{
Header = new Dictionary<String, String>();
MessageType = messageType;
}
为什么 Header
没有问题?这是因为它是在构造函数中新建的。构造函数在反序列化中被调用,因此它被设置,然后添加到字典中,因为每个条目都被反序列化。如果你从构造函数中删除它,你会发现它有同样的问题并且在反序列化后会是 null
.
你好,我想反序列化一个 class 并且在这个 class 中是一个枚举值:
[JsonConverter(typeof(StringEnumConverter))]
public enum MessageType {
Verify,
Disconnect,
}
[Serializable]
public class SocketMessage {
public Dictionary<String, String> Header { get; private set; }
public MessageType MessageType { get; private set; }
public SocketMessage(MessageType type) {
Header = new Dictionary<String, String>();
MessageType = type;
}
public void AddHeaderData(String key, String data) {
Header.Add(key, data);
}
public byte[] ToJSONBytes() {
String json = JsonConvert.SerializeObject(this);
return Encoding.UTF8.GetBytes(json);
}
public static SocketMessage FromJSONBytes(byte[] json) {
String s = Encoding.UTF8.GetString(json);
return JsonConvert.DeserializeObject<SocketMessage>(s);
}
}
字典将被正确反序列化,但枚举总是得到他的默认值>验证< json 看起来像这样:{"Header":{"Test":"Test"},"MessageType" :"断开连接"}
我真的不明白为什么会这样
感谢任何帮助!
由于 MessageType
属性 上的 private set
,它无法正常工作。所以 getter
是 public 所以它序列化很好,但是当涉及到反序列化时,它被忽略了。对此有一些可能的解决方案。
- 对
MessageType
使用 public setter。不过,您首先想要使用私有 setter 可能是有原因的,所以这可能不适合您。 - 将
JsonProperty
属性应用于MessageType
属性:
[JsonProperty]
public MessageType MessageType { get; private set; }
- 将构造函数参数名称更改为
messageType
而不是type
,因此它与序列化名称匹配:
public SocketMessage(MessageType messageType)
{
Header = new Dictionary<String, String>();
MessageType = messageType;
}
为什么 Header
没有问题?这是因为它是在构造函数中新建的。构造函数在反序列化中被调用,因此它被设置,然后添加到字典中,因为每个条目都被反序列化。如果你从构造函数中删除它,你会发现它有同样的问题并且在反序列化后会是 null
.