您可以使用自定義JsonConverter
來處理這種情況。
定義你的數據類是這樣的:
[JsonConverter(typeof(CustomConverter))]
public class RootObject
{
public Dictionary<string, Order> Orders { get; set; }
public string RecsInDB { get; set; }
public string RecsOnPage { get; set; }
}
public class Order
{
[JsonProperty("orders.orderid")]
public string OrderID { get; set; }
[JsonProperty("entity.customerid")]
public string CustomerID { get; set; }
[JsonProperty("entity.entityid")]
public string EntityID { get; set; }
}
創建一個自定義的轉換器來處理根對象是這樣的:
class CustomConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(RootObject));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject jo = JObject.Load(reader);
RootObject obj = new RootObject();
obj.RecsInDB = jo["recsindb"].ToString();
obj.RecsOnPage = jo["recsonpage"].ToString();
obj.Orders = new Dictionary<string, Order>();
foreach (JProperty prop in jo.Properties())
{
if (prop.Name != "recsindb" && prop.Name != "recsonpage")
{
obj.Orders.Add(prop.Name, prop.Value.ToObject<Order>());
}
}
return obj;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
}
然後你就可以反序列化這樣的:
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
現在您可以像平常一樣使用數據類。這裏是一個演示:
class Program
{
static void Main(string[] args)
{
string json = @"
{
""1"": {
""orders.orderid"":""538"",
""entity.customerid"":""109"",
""entity.entityid"":""538"",
},
""2"": {
""orders.orderid"":""536"",
""entity.customerid"":""108"",
""entity.entityid"":""536"",
},
""recsindb"":""2"",
""recsonpage"":""2""
}";
RootObject obj = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine("RecsInDB: " + obj.RecsInDB);
Console.WriteLine("RecsOnPage: " + obj.RecsOnPage);
foreach (var kvp in obj.Orders)
{
Console.WriteLine("Order #" + kvp.Key);
Console.WriteLine(" OrderID " + kvp.Value.OrderID);
Console.WriteLine(" CustomerID " + kvp.Value.CustomerID);
Console.WriteLine(" EntityID " + kvp.Value.EntityID);
}
}
}
輸出:
RecsInDB: 2
RecsOnPage: 2
Order #1
OrderID 538
CustomerID 109
EntityID 538
Order #2
OrderID 536
CustomerID 108
EntityID 536
的可能重複的[REST API的包裝設計:返回動態JSON作爲JSON.NET JObject/JArray](http://stackoverflow.com/questions/22879772/rest-api-wrapper-design-returning-dynamic-json-as-json-net-jobject -jarray) –
我已經標記爲可能的重複問答我幾天前回答。標題是不同的,但它也是你的一個可能的解決方案! –
@MatíasFidemraizer這不像是另一個問題,沒有什麼是像其他問題那樣高度動態。這是一個與屬性混合的字典之間的問題。布賴恩的答案實際上完美地擊中了頭部。 –