我正在调用一个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; }
}
Dictionary<string, object>
。 - Rob