我试图用System.Text.Json
来实现this json,但是我不能,我不知道为什么它不工作,下面是结果:
**PS:我不知道这是否会影响,但元素所在的数组没有名称,只需输入链接并查看PS/2:**这会发生在列表中的任何对象上
下面是我的代码:
using System.Text.Json.Serialization;
namespace AceOfSpadesServersList
{
internal sealed class ServerList
{
[JsonPropertyName("name")]
public string Name { get; internal set; }
[JsonPropertyName("identifier")]
public string IP { get; internal set; }
[JsonPropertyName("map")]
public string Map { get; internal set; }
[JsonPropertyName("game_mode")]
public string GameMode { get; internal set; }
[JsonPropertyName("country")]
public string Country { get; internal set; }
[JsonPropertyName("latency")]
public ushort Latency { get; internal set; }
[JsonPropertyName("players_current")]
public byte CurrentPlayers { get; internal set; }
[JsonPropertyName("players_max")]
public byte MaxPlayers { get; internal set; }
[JsonPropertyName("last_updated")]
public uint LastUpdated { get; internal set; }
[JsonPropertyName("game_version")]
public string GameVersion { get; internal set; }
}
}
using System.IO;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using AceOfSpadesServersList;
namespace AceOfSpadesServersList
{
public class AceOfSpadesServersList
{
private const string BuildAndShootServersList = "http://services.buildandshoot.com/serverlist.json";
private readonly HttpClient _httpClient;
public AceOfSpadesServersList()
{
if (_httpClient is null)
this._httpClient = new HttpClient();
}
public async Task GetAllServersAsync()
{
var json = string.Empty;
var streamHttpResponse = await this._httpClient.GetStreamAsync(BuildAndShootServersList);
using (var sr = new StreamReader(streamHttpResponse, Encoding.UTF8))
json = await sr.ReadToEndAsync();
var serverList = JsonSerializer.Deserialize<ServerList[]>(json);
}
}
}
我不知道出了什么问题,但我使用Newtonsoft.Json
测试了完全相同的代码,我只是将JsonPropertyName
属性更改为JsonProperty
,将JsonSerializer.Deserialize<ServerList[]>(json);
更改为JsonConvert.DeserializeObject<ServerList[]>(json);
,并正常工作,只是在标准C#库中无法工作
3条答案
按热度按时间oyt4ldly1#
System.Text.Json
尊重您对类施加的可见性约束。删除您的setter上的internal
。xggvc2p62#
我也有同样的问题,并通过添加PropertyNamingPolicy来解决它
rryofs0p3#
我可以通过添加PropertyNamingPolicy来解决我的问题。与@ODINSOFT相同。感谢@ODINSOFT!