2013-04-06 95 views
2

我正在開發一個應用程序,它使用Backpack.tf的api在一個名爲TF2的遊戲中獲取玩家揹包值。使用JSON.NET解析JSON在C#中使用JSON.NET

目前的代碼是:

(MAIN CLASS) 
    JsonConvert.DeserializeObject<Json1>(json); 
    (END OF MAIN CLASS) 

public class Json1 { 
    public static List<Json2> response { get; set; } 
} 
public class Json2 
{ 
    public static int success { get; set; } 
    public static int current_time { get; set; } 
    public static IEnumerable<Json4> players { get; set; } 
} 
public class Json4 { 
    public static int steamid { get; set; } 
    public static int success { get; set; } 
    public static double backpack_value { get; set; } 
    public static string name { get; set; } 
} 

我剪了所有其他的廢話了主類等但我只想說,是的,我已經得到了JSON代碼爲JSON字符串準備反序列化(用Console.Writeline測試它)

問題是。每當我使用像Json4.name(當寫入控制檯) 它總是返回0.

對不起,如果我犯了一個愚蠢的錯誤,但我想我已經嘗試了像刪除靜態,改變變量類型等東西,但我仍然無法工作。請注意,這是我第一次嘗試反序列化Json代碼,並且我自己編寫了這些類,因爲某些原因http://json2csharp.com/不起作用。繼承人的Json我試圖反序列化:

{ 
    "response":{ 
     "success":1, 
     "current_time":1365261392, 
     "players":{ 
     "0":{ 
      "steamid":"76561198045802942", 
      "success":1, 
      "backpack_value":12893.93, 
      "backpack_update":1365261284, 
      "name":"Brad Pitt", 
      "stats_tf_reputation":2257, 
      "stats_tf_supporter":1, 
      "notifications":0 
     }, 
     "1":{ 
      "steamid":"76561197960435530", 
      "success":1, 
      "backpack_value":4544.56, 
      "backpack_update":1365254794, 
      "name":"Robin", 
      "notifications":0 
     } 
     } 
    } 
} 

(格式化搞砸一點也請原諒一些拼寫錯誤:))。

+1

所有的字段都是'static'。那些真的應該是非靜態的。 – 2013-04-06 16:13:09

回答

3

你有幾個問題與您的代碼:

一)你所有的領域都是靜態的。去除靜電;你需要他們成爲實例成員。

b)Json1中的響應屬性應該只是一個實例,而不是一個列表。

c)玩家需要是字典(或自定義類型),而不是IEnumerable,因爲它不是JSON中的數組。

d)StreamId具有非常大的數字,不適合int;將其更改爲long(或字符串)。

public class Json1 
{ 
    public Json2 response { get; set; } 
} 

public class Json2 
{ 
    public int success { get; set; } 
    public int current_time { get; set; } 
    public IDictionary<int, Json4> players { get; set; } 
} 

public class Json4 
{ 
    public long steamid { get; set; } 
    public int success { get; set; } 
    public double backpack_value { get; set; } 
    public string name { get; set; } 
} 
+0

感謝這一點,但我從來沒有使用IDictionary類型。我將如何輸出其中的信息?不過謝謝你的迴應。 – LeCoffee 2013-04-06 16:25:49

+1

IDictionary是IEnumerable >,所以你可以像使用相同的循環(foreach我猜),並通過a.Key訪問索引(int)和a.Value訪問值(Json4)。 – outcoldman 2013-04-06 16:42:01

+0

:D我終於明白了,非常感謝你! – LeCoffee 2013-04-06 17:01:04