2012-08-12 221 views
2

我需要這方面的幫助:反序列化JSON對象

我的JSON(這是一個從暗黑破壞神3 API):

{ 
    "name":"Exsanguinating Chopsword of Assault", 
    "icon":"mightyweapon1h_202", 
    "displayColor":"blue", 
    "tooltipParams":"item-data/COGHsoAIEgcIBBXIGEoRHYQRdRUdnWyzFB2qXu51MA04kwNAAFAKYJMD", 
    "requiredLevel":60, 
    "itemLevel":61, 
    "bonusAffixes":0, 
    "dps":{ 
     "min":206.69999241828918, 
     "max":206.69999241828918 
    } 
} 

這不是完整的JSON,但我試圖解析僅此因爲我正在學習它。

我知道如何獲取字符串名稱,圖標,displayColor .....但我不知道如何獲得DPS。

我的模型類:

namespace Diablo_III_Profile 
{ 
[DataContract] 
public class ItemInformation : INotifyPropertyChanged 
{ 
    private string _name; 

    [DataMember] 
    public string name 
    { 
     get 
     { 
      return _name; 
     } 
     set 
     { 
      if (value != _name) 
      { 
       _name = value; 
       NotifyPropertyChanged("name"); 
      } 
     } 
    } 
    //others strings and ints here 

    public event PropertyChangedEventHandler PropertyChanged; 
    private void NotifyPropertyChanged(String propertyName) 
    { 
     PropertyChangedEventHandler handler = PropertyChanged; 
     if (null != handler) 
     { 
      handler(this, new PropertyChangedEventArgs(propertyName)); 
     } 
    } 
} 

什麼是DPS的「格式」把我的模型類?

要讀我使用這個字符串:

MemoryStream ms = new MemoryStream(); 
ItemInformation data = (ItemInformation)Deserialize(ms, typeof(ItemInformation)); 
MessageBox.Show(data.name); 

應該是一樣的DPS?

編輯:

我知道了!如果是說不上來的最佳方式,但....

在我的模型類我把

public class DPS 
    { 
     public float min { get; set; } 
     public float max { get; set; } 
    } 

    private DPS _dps; 

    [DataMember] 
    public DPS dps 
    { 
     get 
     { 
      return _dps; 
     } 
     set 
     { 
      if (value != _dps) 
      { 
       _dps = value; 
       NotifyPropertyChanged("dps"); 
      } 
     } 
    } 
+0

,你能解決問題真棒@阿德爾莫佩雷拉,但你可以用你的解決方案回答你的問題嗎?它會讓其他人更容易找到解決方案,這就是我們希望Sack Overflow的方式。謝謝:) – Daniel 2012-08-12 01:39:26

+0

謝謝@Daniel!它是我第一次使用Stackoverflow來提出問題。 – 2012-08-13 16:38:52

+0

這很酷,歡迎在這裏:)希望你得到你想要的一切,並幫助其他人:) – Daniel 2012-08-13 17:01:46

回答

0

你的解決方案是很好的,這正是我試圖與答覆。通過這種方式,您可以隨時重複使用DPS,並且JSON解析器應該正確地將其反序列化爲「ItemInformation」,其DPS最小值和最大值的值爲正確值。我使用了相同的方法來填充對象和子對象。

您還可以使用JSON.Net進行序列化爲JSON和反序列化JSON對象。

http://james.newtonking.com/projects/json/help/index.html

乾杯

0

我做到了!說不上來,如果是最好的方式,但....

在我的模型類我把

public class DPS 
{ 
    public float min { get; set; } 
    public float max { get; set; } 
} 

private DPS _dps; 

[DataMember] 
public DPS dps 
{ 
    get 
    { 
     return _dps; 
    } 
    set 
    { 
     if (value != _dps) 
     { 
      _dps = value; 
      NotifyPropertyChanged("dps"); 
     } 
    } 
}