序列化的动态属性名称 [英] Dynamic property name for serialization

查看:75
本文介绍了序列化的动态属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

添加返回JObjectToJObject方法.

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.

这篇关于序列化的动态属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆