简体   繁体   English

反序列化JSON以在C#中列出

[英]Deserialize JSON to list in C#

json - http://pastebin.com/Ss1YZsLK json- http://pastebin.com/Ss1YZsLK

I need to get market_hash_name values to list. 我需要列出market_hash_name值。 I can receive first value so far: 到目前为止,我可以得到第一个价值:

using (WebClient webClient = new System.Net.WebClient()) {
    WebClient web = new WebClient();
    var json = web.DownloadString(">JSON LINK<");
    Desc data = JsonConvert.DeserializeObject<Desc>(json);

    Console.WriteLine(data.rgDescriptions.something.market_hash_name);
}

public class Desc {
    public Something rgDescriptions { get; set; }
}

public class Something {
    [JsonProperty("822948188_338584038")]
    public Name something { get; set; }
}

public class Name {
    public string market_hash_name { get; set; }
}

How can I get all if them? 如果他们怎么办?

Since there is no array inside the rgDescriptions but some randomly named looking properties I think you would need a custom JsonConverter. 由于rgDescriptions中没有数组,而是一些随机命名的外观属性,我想您需要一个自定义JsonConverter。 The following console application seems to be working and displaying the market_hash_names correctly: 以下控制台应用程序似乎可以正常工作并正确显示market_hash_names:

class Program
{
    static void Main(string[] args)
    {
        string json = File.ReadAllText("Sample.json");
        Desc result = JsonConvert.DeserializeObject<Desc>(json);
        result.rgDescriptions.ForEach(s => Console.WriteLine(s.market_hash_name));
        Console.ReadLine();
    }
}

public class Desc
{
    [JsonConverter(typeof(DescConverter))]
    public List<Something> rgDescriptions { get; set; }
}

public class Something
{
    public string appid { get; set; }
    public string classid { get; set; }
    public string market_hash_name { get; set; }
}

class DescConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(Something[]);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var descriptions = serializer.Deserialize<JObject>(reader);
        var result = new List<Something>();

        foreach (JProperty property in descriptions.Properties())
        {
            var something = property.Value.ToObject<Something>();
            result.Add(something);
        }

        return result;
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Output: 输出:

Genuine Tactics Pin
Silver Operation Breakout Coin
Operation Phoenix Challenge Coin
Operation Bravo Challenge Coin

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM