0

I have a function that accesses a API and retrieves some Json values, these values are returned and pasted into a rich textbox. How am I able to convert this Json into a object list? The internet is filled with what i am asking but i'm not getting any wiser after reading and trying it all.

This is the function, URL is the Api link that retrieves the Json.

public string GetApi(string url)
        {

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

            try
            {
                WebResponse response = request.GetResponse();
                using (Stream responseStream = response.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
                    return reader.ReadToEnd();
                }
            }
            catch (WebException ex)
            {
                WebResponse errorResponse = ex.Response;
                using (Stream responseStream = errorResponse.GetResponseStream())
                {
                    StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
                    String errorText = reader.ReadToEnd();
                    // log errorText
                }
                throw;
            }
        }

This is the Json structure

{"id":19684,"buys":[{"listings":10,"unit_price":94,"quantity":2498},{"listings":42,"unit_price":93,"quantity":10398},{"listings":139,"unit_price":92,"quantity":34501},{"listings":8,"unit_price":91,"quantity":1939},{"listings":38,"unit_price":90,"quantity":9270},{"listings":7,"unit_price":89,"quantity":1266},{"listings":43,"unit_price":88,"quantity":10565},{"listings":23,"unit_price":87,"quantity":5476},{"listings":80,"unit_price":86,"quantity":19827},
3
  • Codes for retrieving the JSON isn't relevant to the question about converting JSON to list. What have you tried to do the conversion specifically? That would be more relevant to post... Commented Apr 2, 2015 at 0:51
  • @har07 I keep being pointed back at serialization and otherwise using structs. Commented Apr 2, 2015 at 0:59
  • What's wrong with serialization? Any specific reason to avoid serialization? That's a clean way IMHO to convert your JSON to a more friendly .NET object through serialization Commented Apr 2, 2015 at 1:09

1 Answer 1

1

The first order of business is to use a library to parse the JSON. For this answer I use Newtonsoft.Json, one of the most used JSON libraries for .NET.

Then, the structure of the document you receive from the server should be identified. I'm just guessing here, but I assume it's something like the classes defined below. The JsonProperty is an attribute to specify the field name from the JSON document mapping to the property. It isn't necessary to specify this, only when your property names are different from the field names in the JSON document. In this case, unit_price does not match the standard .NET PascalCase naming convention for properties.

public class Listings
{
    [JsonProperty(PropertyName = "id")]
    public int Id { get; set; }

    public List<Buy> Buys { get; private set; }

    public Listings()
    {
        Buys = new List<Buy>();
    }
}
public class Buy
{
    [JsonProperty(PropertyName = "listings")]
    public int Listings { get; set; }

    [JsonProperty(PropertyName = "unit_price")]
    public int UnitPrice { get; set; }

    [JsonProperty(PropertyName = "quantity")]
    public int Quantity { get; set; }
}

Once you have defined the class structure, you can let the library do all of the work. Look into the documentation for more details, here is how you would retrieve the list inside the method you already wrote.

public Listings GetApi(string url)
{
    ...
        using (Stream responseStream = response.GetResponseStream())
        {
            StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
            var jsonReader = new JsonTextReader(reader);
            var serializer = new JsonSerializer();
            return serializer.Deserialize<Listings>(jsonReader);
        }
    ...
}
Sign up to request clarification or add additional context in comments.

7 Comments

How do I access the object in my other main class?
@KrijnvanderBurg how do you access your string in your other main class? It's the result of the method call.
You mean how i accessed the Json string? I used this as value api_Request.GetApi("https://api.guildwars2.com/v2/commerce/listings/19684");
You do string xxx = api_Request..... Instead of that you can do Listings xxx = api_Request....
I was using a richtextbox. When trying to apply what you just said i get error it doesnt know the dot in ".text". Removing the .text returns a error: Cannot convert object to GW2_tradingPost.Listings I assume its simply because you can not send objects to a textbox?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.