【问题标题】:Deserialize json to static member c#将json反序列化为静态成员c#
【发布时间】:2016-07-13 01:16:25
【问题描述】:

我有两个如下所示的类:

public class Field
{
    public string Name { get; set; }
    public FieldType FieldType { get; set; }
}

public class FieldType
{
    public Dictionary<string, object> Settings { get; set; }

    public static readonly FieldType Text = new FieldType()
    {
        Settings = new Dictionary<string, object>() { { "setting 1", "" }, { "setting 2", "" } }
    };
}

我想反序列化以下 json:

{
    "name": "First Name",
    "fieldType": "Text"
}

以便为 FieldType 属性正确分配“Text”的静态 FieldType。

我需要修改我的 FieldType 类吗?还是我需要一些自定义的 JsonSerializerSettings?

目前我收到错误:将值“Text”转换为“FieldType”时出错。路径'fieldType

【问题讨论】:

  • 因为FieldType是一个类,被序列化为字符串属性

标签: c# json json.net


【解决方案1】:

您的 json 的外观涉及到 fieldType 作为字符串类型的实例,因此如果您将要反序列化的类更改为类似:

public class Field
{
    public string Name { get; set; }
    public string FieldType { get; set; }
}

反序列化将起作用。

我需要修改我的 FieldType 类吗?

不,您不需要修改 FieldType 类,您可以保持原样,反序列化为 Field,然后使用字段类中的值填充您的 FieldType 类或做任何你想做的事。

您不能反序列化为静态属性,您可以查看this question 了解更多详细信息。如果您需要将数据存储在静态字段中,并将其接收到静态字段中,那么您不应该尝试使用序列化。

【讨论】:

  • FieldType 只能是固定数量的值之一。有没有更好的方法可以将字符串 text 转换为 FieldType 成员,而无需在 Field 类中使用此虚拟属性?
  • @EdB 我已经更新了我的答案,希望现在很清楚。
【解决方案2】:

可以使用DataContactJsonSerializer的ReadObject方法

DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Field));
MemoryStream stream1 = new MemoryStream();
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);

Field field = (Field)ser.ReadObject(stream1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-08-21
    • 1970-01-01
    • 2011-04-28
    • 2011-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多