序列化的动态属性名称

编程入门 行业动态 更新时间:2024-10-27 22:22:17
本文介绍了序列化的动态属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我需要一个动态的属性名称来进行序列化.

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.

更多推荐

序列化的动态属性名称

本文发布于:2023-11-14 21:32:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1588552.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   名称   序列化   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!