本文介绍了序列化的动态属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个动态的属性名称来进行序列化.
I need to have a dynamic property-name for the serialization.
public class Home { public virtual int Id { get; set; } // value: 2 public virtual string propertyName { get; set; } // value: administration public virtual string Text { get; set; } // value: text1 }应序列化为:
{ "Id": 2, "administration": "text1" }有什么方法可以序列化吗?反序列化的最佳方法是哪种?
Is there any way to serialize that? Which is the best way to deserialize it?
推荐答案添加返回JObject的ToJObject方法.
public JObject ToJObject() { JObject jObject = new JObject() { { "Id", Id }, { propertyName, Text } } return jObject; }然后为Deserializing创建一个工厂方法,如下所示:
Then for Deserializing i would probably create a factory method something like this:
public static Home CreateFromJObject(JObject obj) { Home h = new Home(); foreach (var a in obj) { if (a.Key == "ID") { h.Id = a.Value.Value<int>(); } else { h.propertyName = a.Key; h.Text = a.Value.Value<string>(); } } return h; }因为如果在那里有多个其他值,我要么将其更改为一个开关,要么确保仅将所需的JObject传递到那里.
Ofcause if you have multiple other values in there i would either change it to a switch or make sure that only the needed JObject is passed in there.
更多推荐
序列化的动态属性名称
发布评论