簡體   English   中英

C#反序列化JSON API響應

[英]C# Deserialize json api response

嘿,我想反序列化此json API響應以獲取包括配置文件狀態等在內的值,以便在程序中進行處理。 我從這里的不同問題嘗試了多種方法,但得到的響應為null。 這是代碼,請糾正我我在做什么錯

{
    "response": {
        "players": [{
            "steamid": "xxxxxxxxxxxxxxxxx",
            "communityvisibilitystate": 3,
            "profilestate": 1,
            "personaname": "xxxx xxxx",
            "lastlogoff": 1529478555,
            "commentpermission": 1,
            "profileurl": "xxxxxxxxxxxxxxx",
            "avatar": "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
            "avatarmedium": "xxxxxxxxxxxxxxxxxxxxx",
            "avatarfull": "xxxxxxxxxxx",
            "personastate": 1,
            "realname": "xxxx",
            "primaryclanid": "xxxxxxxxxx",
            "timecreated": 1097464215,
            "personastateflags": 0
        }]
    }
}

我試過的代碼

public class AccountInfo
    {
        public string steamid { get; set; }
        public int communityvisibilitystate { get; set; }
        public int profilestate { get; set; }
        public string personaname { get; set; }
        public ulong lastlogoff { get; set; }
        public int commentpermission { get; set; }
        public string profileurl { get; set; }
        public string avatar { get; set; }
        public string avatarmedium { get; set; }
        public string avatarfull { get; set; }
        public int personastate { get; set; }
        public string realname { get; set; }
        public string primaryclanid { get; set; }
        public ulong timecreated { get; set; }
        public int personastateflags { get; set; }
    }

    public class Response
    {
        public AccountInfo response { get; set; }
    }

    public class Response1
    {
        public Response players { get; set; }
    }

    static void Main(string[] args)
    {
        DeserilizeJson();
    }

    internal static void DeserilizeJson()
    {
        string json = GetUrlToString("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=xxxxxxxxxxxxxxxxxxxxx&steamids=xxxxxxxxxxxxxxx");
        Console.WriteLine(json);
        Response1 info = JsonConvert.DeserializeObject<Response1>(json);

        using (StreamWriter file = File.CreateText(@"c:\test.json"))
        {
            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(file, info);
        }
    }

    internal static string GetUrlToString(string url)
    {
        String Response = null;

        try
        {
            using (WebClient client = new WebClient())
            {
                Response = client.DownloadString(url);
            }
        }
        catch (Exception)
        {                
            return null;
        }

        return Response;
    }

將此用作模型類

 using System;
    using System.Collections.Generic;

    using System.Globalization;
    using Newtonsoft.Json;
    using Newtonsoft.Json.Converters;

    public partial class JsonModel
    {
        [JsonProperty("response")]
        public Response Response { get; set; }
    }

    public partial class Response
    {
        [JsonProperty("players")]
        public List<Player> Players { get; set; }
    }

    public partial class Player
    {
        [JsonProperty("steamid")]
        public string Steamid { get; set; }

        [JsonProperty("communityvisibilitystate")]
        public long Communityvisibilitystate { get; set; }

        [JsonProperty("profilestate")]
        public long Profilestate { get; set; }

        [JsonProperty("personaname")]
        public string Personaname { get; set; }

        [JsonProperty("lastlogoff")]
        public long Lastlogoff { get; set; }

        [JsonProperty("commentpermission")]
        public long Commentpermission { get; set; }

        [JsonProperty("profileurl")]
        public string Profileurl { get; set; }

        [JsonProperty("avatar")]
        public string Avatar { get; set; }

        [JsonProperty("avatarmedium")]
        public string Avatarmedium { get; set; }

        [JsonProperty("avatarfull")]
        public string Avatarfull { get; set; }

        [JsonProperty("personastate")]
        public long Personastate { get; set; }

        [JsonProperty("realname")]
        public string Realname { get; set; }

        [JsonProperty("primaryclanid")]
        public string Primaryclanid { get; set; }

        [JsonProperty("timecreated")]
        public long Timecreated { get; set; }

        [JsonProperty("personastateflags")]
        public long Personastateflags { get; set; }
    }

然后在您的主班上做

     var info = JsonConvert.DeserializeObject<JsonModel>(json);
var Response = info.Response

嘗試這個:

public class Player
{
    public string steamid { get; set; }
    public int communityvisibilitystate { get; set; }
    public int profilestate { get; set; }
    public string personaname { get; set; }
    public ulong lastlogoff { get; set; }
    public int commentpermission { get; set; }
    public string profileurl { get; set; }
    public string avatar { get; set; }
    public string avatarmedium { get; set; }
    public string avatarfull { get; set; }
    public int personastate { get; set; }
    public string realname { get; set; }
    public string primaryclanid { get; set; }
    public ulong timecreated { get; set; }
    public int personastateflags { get; set; }    
}

public class Response
{
    public Player[] players { get; set; }
}

public class EncapsulatedResponse
{
    public Response response {get;set;}
}

internal static void DeserilizeJson()
{
    string json = GetUrlToString("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=xxxxxxxxxxxxxxxxxxxxx&steamids=xxxxxxxxxxxxxxx");
    Console.WriteLine(json);
    EncapsulatedResponse info = JsonConvert.DeserializeObject<EncapsulatedResponse>(json);

    using (StreamWriter file = File.CreateText(@"c:\test.json"))
    {
        JsonSerializer serializer = new JsonSerializer();
        serializer.Serialize(file, info);
    }
}

players屬性應該是玩家列表,因為它是一個數組。 下面是正確的模型

 public class Player
{
    public string steamid { get; set; }
    public int communityvisibilitystate { get; set; }
    public int profilestate { get; set; }
    public string personaname { get; set; }
    public int lastlogoff { get; set; }
    public int commentpermission { get; set; }
    public string profileurl { get; set; }
    public string avatar { get; set; }
    public string avatarmedium { get; set; }
    public string avatarfull { get; set; }
    public int personastate { get; set; }
    public string realname { get; set; }
    public string primaryclanid { get; set; }
    public int timecreated { get; set; }
    public int personastateflags { get; set; }
}

public class Response
{
    public List<Player> players { get; set; }
}
  1. 打開nuget,搜索newtonsoft.json並安裝。
  2. 反序列化:

    var deserialized = JsonConvert.DeserializeObject(jsonstring);

您需要更改對象結構:

public class Response
{
    public AccountInfo[] players { get; set; }
}

public class Response1
{
    public Response response { get; set; }
}

然后反序列化Response1(就像您當前所做的那樣)

只需提供一種不同的方法,就可以使用JObject (Newtonsoft.Json.Linq),以便只需要AccountInfo類:

var accounts = JObject.Parse(json).Root
    .SelectToken("response.players")
    .ToObject(typeof(AccountInfo[]));

或者在某些情況下,導航屬性甚至更容易:

var accounts = JObject.Parse(json)["response"]["players"]
    .ToObject((typeof(AccountInfo[])));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM