2012-07-12 32 views
10

Tôi muốn phân tích cú pháp đoạn JSON này trong C# bằng JSON.NET, nhưng tôi không biết cách làm thế nào để thực hiện nó.Phân tích cú pháp json trong C# mà không biết các chỉ mục

Json:

{ 
    "success":true, 
    "rgInventory":{ 
     "967633758":{ 
      "id":"967633758", 
      "classid":"23973033", 
      "instanceid":"11040671", 
      "amount":"1", 
      "pos":1 
     }, 
     "302756826":{ 
      "id":"302756826", 
      "classid":"15", 
      "instanceid":"11041143", 
      "amount":"1", 
      "pos":2 
     },... 
    } 
} 

Full Json: http://steamcommunity.com/id/jessecar/inventory/json/440/2/?trading=1

tôi cần để có được các yếu tố của mỗi "rgInventory" đứa trẻ, nhưng tôi không thể làm cho một lớp học cho nó vì tên item luôn thay đổi.

Tôi đã thử sử dụng đoạn mã này nhưng tôi luôn nhận được ngoại lệ.

dynamic jsObject = JsonConvert.DeserializeObject(jsonString); 

Console.WriteLine("Status: "+jsObject["success"]); //This works fine 

foreach(var i in jsObject["rgInventory"]){ 
    Console.WriteLine("Item ID: "+i["id"]); //This gives an exception 
} 

Ngoại lệ:

Unhandled Exception: System.InvalidOperationException: Không thể truy cập giá trị con trên Newtonsoft.Json.Linq.JProperty.

Trả lời

12

Điều này sẽ hiệu quả.

var jObj = (JObject)JsonConvert.DeserializeObject(json); 
foreach(var child in jObj["rgInventory"].Children()) 
{ 
    Console.WriteLine("Item ID: {0}", child.First()["id"]); 
} 

Bên cạnh đó, sử dụng dynamic từ khóa có thể làm cho mã của bạn readible hơn:

dynamic jObj = JsonConvert.DeserializeObject(json); 
Console.WriteLine("Status: " + jObj.success); 
foreach(var child in jObj.rgInventory.Children()) 
{ 
    Console.WriteLine("Item ID: {0}", child.First.id); 
} 
+1

làm việc hoàn hảo, Cảm ơn bạn! – Jessecar

Các vấn đề liên quan