简体   繁体   中英

Deserialize JSON string into a list for dropdownlist in C#

I have a windows form application and would like to deserialize a JSON string that I'm getting from a web address so that I can get just two values from it, how would I go about doing this?

Below is the code I have to get the JSON string, and if you go to the URL that it's getting, you can also see the JSON string. I want to just get the item name, and current price of it. Which you can see the price under the current key.

        private void GrabPrices()
    {
        using (WebClient webClient = new System.Net.WebClient())
        {
            WebClient n = new WebClient();
            var json = n.DownloadString("http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item=1513");
            string valueOriginal = Convert.ToString(json);
            Console.WriteLine(json);

        }
    }

It's also going to be iterating through a SQLite database and getting the same data for multiple items based on the item ID, which I'll be able to do myself.

EDIT I'd like to use JSON.Net if possible, I've been trying to use it and it seems easy enough, but I'm still having trouble.

Okay so first of all you need to know your JSON structure, sample:

[{
   name: "Micheal",
   age: 20
 },
 {
   name: "Bob",
   age: 24
}]

With this information you can derive a C# object

public class Person
{
   public string Name {get;set;}
   public int Age {get;set;}
}

Now you can use JSON.NET to deserialize your JSON into C#:

var people = JsonConvert.DeserializeObject<List<Person>>(jsonString);

If you look at the original JSON it is an array of objects, to deal with this I have used List<T> .

Key things to remember, you need to have the C# object mirror in properties that of the JSON object. If you don't have a list, then you don't need List<T> .

If your JSON objects have camel casing, and you want this converted to the C# conventions, then use this:

var people = JsonConvert.DeserializeObject<List<Person>>(
                 jsonString,
                 new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });

First of all you need to create a class structure for the JSON

public class Wrapper
{
    public Item item;
}
public class Item
{
    public string icon { get; set; }
    public string icon_large { get; set; }
    public int id { get; set; }
    public string type { get; set; }
    public string typeIcon { get; set; }
    public string name { get; set; }
    public string description { get; set; }
    public GrandExchange current { get; set; }
    public GrandExchange today { get; set; }
    public bool members { get; set; }
    public GrandExchange day30 { get; set; }
    public GrandExchange day90 { get; set; }
    public GrandExchange day180 { get; set; }
}

public class GrandExchange
{
    public string trend { get; set; }
    public string price { get; set; }
}

Then you need to serialize the current item into a Wrapper class

var wrapper = JsonConvert.DeserializeObject<Wrapper>(json);

Then if you want multiple items in a list, you can do so with this code :

// Items to find
int[] itemIds = {1513, 1514, 1515, 1516, 1517};
// Create blank list
List<Item> items = new List<Item>();

foreach (int id in itemIds)
{
    var n = new WebClient();
    // Get JSON
    var json = n.DownloadString(String.Format("http://services.runescape.com/m=itemdb_rs/api/catalogue/detail.json?item={0}", id));
    // Parse to Item object
    var wrapper = JsonConvert.DeserializeObject<Wrapper>(json);

    // Append to list
    items.Add(wrapper.item);
}
// Do something with list

It is also worth noting that Jagex limit how many times this API can be called from a certain IP within a time frame, going over that limit will block your IP for a certain amount of time. (Will try and find a reference for this)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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