我正在尝试使用Json.Net从动态对象读取数据,我使用webclient.downloadString获取json字符串。
{
"player1": {
"id": 21426685,
"name": "player1",
"profileIconId": 508,
"revisionDate": 1436353103000,
"Level": 30
},
"Player2": {
"id": 27864632,
"name": "player2",
"profileIconId": 508,
"revisionDate": 1436444512000,
"Level": 30
}
}
每次根据api调用,属性名称(播放器)都会有所不同。 我可以使用Json.net反序列化json字符串并获取每个属性的名称,但我无法弄清楚如何获取每个属性的数据,因为它没有常量名称
Dim jsonobj As Object = JsonConvert.DeserializeObject(ChampionsReply)
For Each p As JProperty In jsonobj
ListBox1.Items.Add(p.Name)
Next
任何人都可以指出我的方法让它发挥作用吗?
答案 0 :(得分:1)
使用带有字符串键的词典(用于动态键),然后使用Player对象,而不是动态,尝试数据结构。
var response = JsonConvert.DeserializeObject<Dictionary<string, Player>>(ChampionsReply);
foreach (var key in response.Keys)
ListBox1.Items.Add(response[key].Name); // Get player by key
public class Player
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("profileIconId")]
public int ProfileIconId { get; set; }
[JsonProperty("revisionDate")]
public long RevisionDate { get; set; }
[JsonProperty("level")]
public int Level { get; set; }
}
在VB.NET中:
Dim response = JsonConvert.DeserializeObject(Of Dictionary(Of String, Player))(ChampionsReply)
For Each key As String In response.Keys
response(key).Id
Next
Public Class Player
<JsonProperty("id")> _
Public Property Id() As String
Get
Return m_Id
End Get
Set
m_Id = Value
End Set
End Property
Private m_Id As String
<JsonProperty("name")> _
Public Property Name() As String
Get
Return m_Name
End Get
Set
m_Name = Value
End Set
End Property
Private m_Name As String
<JsonProperty("profileIconId")> _
Public Property ProfileIconId() As Integer
Get
Return m_ProfileIconId
End Get
Set
m_ProfileIconId = Value
End Set
End Property
Private m_ProfileIconId As Integer
<JsonProperty("revisionDate")> _
Public Property RevisionDate() As Long
Get
Return m_RevisionDate
End Get
Set
m_RevisionDate = Value
End Set
End Property
Private m_RevisionDate As Long
<JsonProperty("level")> _
Public Property Level() As Integer
Get
Return m_Level
End Get
Set
m_Level = Value
End Set
End Property
Private m_Level As Integer
End Class