将JSON反序列化为对象,包括部分动态属性

4

我正在调用一个rest服务,该服务返回JSON内容。大部分内容具有预定义的结构,但某些内容根据传递给REST服务的参数而动态生成。 在从rest服务获取响应后,我想反序列化为对象,以便轻松使用数据。我当前正在使用DataContractJsonSerializer来实现。

/// <summary>
/// Deserialize JSON formatted string to an object of a specified type
/// </summary>
/// <typeparam name="T">Object type to deserialize</typeparam>
/// <param name="sJSON">JSON formatted string to deserialize</param>
/// <returns>Returns an instance of an object</returns>
public static T FromJSON<T>(this string sJSON) where T : new()
{
    T oValue;

    using (System.IO.MemoryStream strJSON = new System.IO.MemoryStream())
    {
        using (System.IO.StreamWriter swJSON = new System.IO.StreamWriter(strJSON))
        {
            swJSON.Write(sJSON);
            swJSON.Flush();

            strJSON.Seek(0, System.IO.SeekOrigin.Begin);

            System.Runtime.Serialization.Json.DataContractJsonSerializer ser = new System.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(T));
            oValue = (T)ser.ReadObject(strJSON);

            return oValue;
        }
    }
}

以下是 Rest 服务响应的示例:
{
    "entities" : [{
            "type" : "mytest",
            "properties" : {
                "Active" : true,
                "Category" : "10732",
                "Description" : "test test test",
                "LastUpdateTime" : 1446676525195,
                "Id" : "12655"
            }
        }
    ],
    "metadata" : {
        "status" : "OK",
        "count" : 0
    }
}

该对象始终具有“entities”和“metadata”属性,元数据始终具有“status”和“count”属性,实体始终是一个数组,数组中的每个项都将具有“type”和“properties”属性。动态性体现在属性对象中,该对象完全基于传递到REST服务的内容包含属性。
这是我一直在使用的类定义将json字符串反序列化为对象。但我不确定如何使属性部分变得动态。即使最终可以得到名称值字典,也是可行的。这是可能的,最好不需要第三方json库?
[DataContract]
public class Response
{
    [DataMember(
    public Entity[] entities { get; set; }

    [DataMember(
    public MetaData metadata { get; set; }
}

[DataContract]
public class Entity
{
    [DataMember(
    public string type { get; set; }  

    [DataMember()]
    public Properties properties { get; set; }
}


[DataContract]
public class Properties
{
     //How do I make this part dynamic?
}

[DataContract]
public class MetaData
{
    [DataContract]
    public enum Status
    {
        [EnumMember]
        OK,

        [EnumMember]
        FAILED
    }

    public Status CompletionStatus { get; set; }

    [DataMember()]
    public string status
    {
        get
        {
            return this.CompletionStatus.ToString();
        }
        set
        {
            this.CompletionStatus = (Status)Enum.Parse(typeof(Status), value);
        }
    }

    [DataMember()]
    public int count{ get; set; }
}

2
将属性设置为 Dictionary<string, object> - Rob
@Rob - 看起来不起作用。 "Properties" 属性始终具有计数为0的特性。 - Jeremy
仔细看了一下 - 您还需要配置序列化器以正确序列化JSON对象/字典 - 请参见发布的答案 - Rob
2个回答

3

将您的属性更改为以下内容:

[DataMember]
public Dictionary<string, object> properties { get; set; }

然后您需要配置序列化程序:

var ser = new DataContractJsonSerializer(typeof(T), new DataContractJsonSerializerSettings {
    UseSimpleDictionaryFormat = true 
});

另外,如果您使用JSON.net进行序列化,它将自动处理它。 - Duncan Watts
1
哦,太棒了!比我采用的方法要好得多,我的方法是创建一个实现ISerializable接口的类,然后使用Constructor(SerializationInfo info, StreamingContext context)构造函数。 - Jeremy
这是正确的答案,因为大多数对象具有固定的结构,只有属性是动态的。其他答案使整个对象都变成了动态的。 - intotecho

1
我将你的代码放入控制台应用程序中并进行了一些试验,你想要使用的是称为动态类型的东西。
这是我的代码:
static void Main(string[] args)
{
        string test = @" [{
        ""type"" : ""mytest"",
        ""properties"" : {
            ""Active"" : true,
            ""Category"" : ""10732"",
            ""Description"" : ""test test test"",
            ""LastUpdateTime"" : 1446676525195,
            ""Id"" : ""12655""
        }
    },
{
        ""type"" : ""mytest1"",
        ""properties"" : {
            ""Active"" : true,
            ""Category"" : ""10731232"",
            ""Description"" : ""test test1 test"",
            ""LastUpdateTime"" : 144195,
            ""Id"" : ""126155""
        }
    }
]";
        List<Entity> entities = JsonConvert.DeserializeObject<List<Entity>>(test);
        foreach (Entity e in entities)
        {
            Console.WriteLine(e.properties.Active);
        }
        Console.ReadKey();
}

Here is my class:

public class Entity
    {
         public string type { get; set; }
        public dynamic properties { get; set; }
    }

因为属性是动态的,它从你的JSon获取数据并决定其结构需要看起来像什么。我使用Newtsoft进行反序列化,但概念应该保持不变。 同时要小心,由于它是动态的,一些类型,如布尔值,可能无法正确传输,因此确保在C#中获取它们时匹配其正确的类型。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接