[英]Newtonsoft JSON serialize a template
我正在尝试将一个类序列化为JSON字符串。 首先,我的实际代码:
// Note that this class is inside a PCL
public class CommunicationMessage {
public String Key { get; set; }
public String Value { get; set; }
public List<CommunicationMessage> Childs { get; set; }
}
这是一个模板,可以转换为如下所示的xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<myproject>
<communicationmessage>
<header>
<participantid>1</participantid>
<deviceid>54325</deviceid>
<devicetype>Smartphone Samsung 4500</devicetype>
<timestamp>3456453445</timestamp>
<location>343-5343-64353</location>
<networkid>32</networkid>
<messageid>4003</messageid>
</header>
<data>
</data>
</communicationmessage>
</myproject>
如您所见,变量Key是一个Xml-Element,其名称例如为communicationmessage 。
现在,您希望将模板信息转换为JSON字符串,但是可以肯定的是,我获得了元素“ Key”:“ communicationmessage”而不是元素communicationmessage 。 是否有办法为“ mymessage”这样的元素获取某些东西:“这是测试” ,其中“ mymessage”是键,而“这是测试”是值?
谢谢你的帮助
我用这段代码解决了
public class CommunicationMessageJSONSerializer : JsonConverter {
/// <summary>
/// Used to
/// </summary>
/// <param name="objectType"></param>
/// <returns></returns>
public override bool CanConvert(Type objectType) {
return typeof(CommunicationMessage).GetTypeInfo().IsAssignableFrom(objectType.GetTypeInfo());
}
/// <summary>
/// Deserializes the JSON string
/// </summary>
/// <param name="reader"></param>
/// <param name="objectType"></param>
/// <param name="existingValue"></param>
/// <param name="serializer"></param>
/// <returns></returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) {
// Load the JSON object from the reader
JObject jsonObject = JObject.Load(reader);
// Get the First Token
JToken token = jsonObject.Children().First();
// The deserialized message
CommunicationMessage msg = ReadJSON(token);
return msg;
}
/// <summary>
/// This is the base method when deserializing a JSON string
/// </summary>
/// <param name="token"></param>
/// <returns>The root CommunicationMessage</returns>
private CommunicationMessage ReadJSON(JToken token) {
CommunicationMessage root = new CommunicationMessage();
if (token is JProperty) {
if (token.First is JValue) {
root.Key = ((JProperty)token).Name;
root.Value = (string)((JProperty)token).Value;
} else {
root.Key = ((JProperty)token).Name;
foreach (JToken child in token.Children()) {
ReadRecursive(child, ref root);
}
}
} else {
foreach (JToken child in token.Children()) {
ReadRecursive(child, ref root);
}
}
return root;
}
/// <summary>
/// This is the recursive method when deserializing a JSON string
/// </summary>
/// <param name="token"></param>
/// <param name="root">The root of the coming messages</param>
private void ReadRecursive(JToken token, ref CommunicationMessage root) {
if (token is JProperty) {
CommunicationMessage msg = new CommunicationMessage();
if (token.First is JValue) {
msg.Key = ((JProperty)token).Name;
msg.Value = (string)((JProperty)token).Value;
} else {
msg.Key = ((JProperty)token).Name;
foreach (JToken child in token.Children()) {
ReadRecursive(child, ref msg);
}
}
root.Childs.Add(msg);
} else {
foreach (JToken child in token.Children()) {
ReadRecursive(child, ref root);
}
}
}
/// <summary>
/// Serializes a CommuicationMessage to a JSON string
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="serializer"></param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) {
var msg = value as CommunicationMessage;
WriteRecoursive(writer, msg, serializer);
}
/// <summary>
/// This is the recursive method for serializing
/// </summary>
/// <param name="writer"></param>
/// <param name="msg"></param>
/// <param name="serializer"></param>
private void WriteRecoursive(JsonWriter writer, CommunicationMessage msg, JsonSerializer serializer) {
writer.WriteStartObject();
writer.Formatting = Formatting.Indented;
writer.WritePropertyName(msg.Key);
if (msg.Childs.Count > 0) {
writer.WriteStartArray();
foreach (CommunicationMessage child in msg.Childs) {
WriteRecoursive(writer, child, serializer);
}
writer.WriteEndArray();
} else {
writer.WriteValue(msg.Value);
}
writer.WriteEndObject();
}
}
如果您有任何改进代码的想法,请告诉我。 我将保持解决方案更新。
谢谢大家的帮助
除了使用自定义序列化或实现ISerializable之外 ,您还可以执行以下操作。 但是请注意,此方法有一个缺点,即所有属性都必须像这样包装,否则属性将不会被序列化。 这种快速而肮脏的方法对于小型类是好的,但是如果您要创建更复杂的类,则实现ISerializable会更好。
public class CommunicationMessage : Dictionary<string, object>
{
//this "hack" exposes the "Child" as a List
public List<CommunicationMessage> Childs
{
get {
return (List<CommunicationMessage>)this["Childs"];
}
set
{
this["Childs"] = value;
}
}
public CommunicationMessage()
{
this["Childs"] = new List<CommunicationMessage>();
}
}
用法:
var m = new CommunicationMessage();
m["mymessage"] = "This is a test";
和输出应该看起来像
{
"Childs": [],
"mymessage": "This is a test"
}
可替代的ISerializable实现:
public class CommunicationMessage:ISerializable
{
public String Key { get; set; }
public String Value { get; set; }
public List<CommunicationMessage> Childs { get; set; }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue(Key, Value);
PropertyInfo[] pi=this.GetType().GetProperties();
foreach(var p in pi)
{
if (p.Name == "Key" || p.Name == "Value")
continue;
info.AddValue(p.Name, p.GetValue(this));
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.