unable to put deserialized json into gridview - c#

Gridview unable to get json data due to invalid data type. From what i understand it needs a List<> data source. How do i make my data populate my gridview?
The received JSON from the api
{"BTC":{"SGD":4864.11,"USD":3617.33,"EUR":3162.71}}
...
public class BTC
{
public double SGD { get; set; }
public double USD { get; set; }
public double EUR { get; set; }
}
public class CryptoPrice
{
public BTC BTC { get; set; }
}
...
var webRequest = (HttpWebRequest)WebRequest.Create("https://min-api.cryptocompare.com/data/pricemulti?fsyms=BTC&tsyms=SGD,USD,EUR&api_key=<secret_key>");
var webResponse = (HttpWebResponse)webRequest.GetResponse();
if (webResponse.StatusCode == HttpStatusCode.OK)
{
JavaScriptSerializer json = new JavaScriptSerializer();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
string resString = sr.ReadToEnd();
CryptoPrice list = json.Deserialize<CryptoPrice>(resString);
GridView1.DataSource = list.BTC;
GridView1.DataBind();
}

I’m not 100% sure but your data source is not a list. As you can see in your code you’re deserializing returned Json to only one instance of CryptoPrice type. Try deserializing it to List<CryptoPrice> and assign it as data source to your grid view.

Related

Read specific object data from json

I want to get specific object data from json from url the following code give me. i need the second object 'EmailAddressSuffices'
WebRequest request = WebRequest.Create(
"https://atea-dev.accesscontrol.windows.net/v2/metadata/IdentityProviders.js?protocol=wsfederation&realm=https%3a%2f%2flocalhost%3a44300%2fAccount%2fLoginCallback%2f&reply_to=https%3a%2f%2flocalhost%3a44300%2fAccount%2fLoginCallback%2f&context=&request_id=&version=1.0&callback=");
request.Credentials = CredentialCache.DefaultCredentials;
WebResponse response = request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
Using JSON.Net you can deserialize the JSON response easily:
Solution 1
1. Create a class to map your JSON into:
public class ResponseObject
{
[JsonProperty("Name")]
public string Name { get; set; }
[JsonProperty("LoginUrl")]
public string LoginUrl { get; set; }
[JsonProperty("LogoutUrl")]
public string LogoutUrl { get; set; }
[JsonProperty("ImageUrl")]
public string ImageUrl { get; set; }
[JsonProperty("EmailAddressSuffixes")]
public IList<string> EmailAddressSuffixes { get; set; }
}
2. Deserialize your JSON using JsonConvert.Deserialize<ResponseObject>()
var myresponse = JsonConvert.DeserializeObject<List<ResponseObject>>(responseFromServer);
string email = myresponse[1].EmailAddressSuffixes[0];
Solution 2
If you don't want to bother with derializing the entire thing then you can do this:
JArray array = JArray.Parse(responseFromServer);
string q = array[1]["EmailAddressSuffixes"][0].ToString();
But you should make sure that your object has the right format (and the right number of items in the array.

Easiest way to parse JSON response

Is there any easy way to parse below JSOn in c#
{"type":"text","totalprice":"0.0045","totalgsm":"1","remaincredit":"44.92293","messages": [
{"status":"1","messageid":"234011120530636881","gsm":"923122699633"}
]}
and in case Multiple results.
Follow these steps:
Convert your JSON to C# using json2csharp.com;
Create a class file and put the above generated code in there;
Add the Newtonsoft.Json library to your project using the Nuget Package Manager;
Convert the JSON received from your service using this code:
RootObject r = JsonConvert.DeserializeObject<RootObject>(json);
(Feel free to rename RootObject to something more meaningful to you. The other classes should remain unchanged.)
You can safely use built-in JavaScriptSerializer without referencing additional third party libraries:
var ser = new System.Web.Script.Serialization.JavaScriptSerializer();
ser.DeserializeObject(json);
I found a way to get it without using any external API
using (var w = new WebClient())
{
var json_data = string.Empty;
string url = "YOUR URL";
// attempt to download JSON data as a string
try
{
json_data = w.DownloadString(url);
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
var result = jsSerializer.DeserializeObject(json_data);
Dictionary<string, object> obj2 = new Dictionary<string, object>();
obj2=(Dictionary<string,object>)(result);
string val=obj2["KEYNAME"].ToString();
}
catch (Exception) { }
// if string with JSON data is not empty, deserialize it to class and return its instance
}
For me ... the easiest way to do that is using JSON.net do a deserialize to a entity that represents the object, for example:
public class Message
{
public string status { get; set; }
public string messageid { get; set; }
public string gsm { get; set; }
}
public class YourRootEntity
{
public string type { get; set; }
public string totalprice { get; set; }
public string totalgsm { get; set; }
public string remaincredit { get; set; }
public List<Message> messages { get; set; }
}
And do this:
YourRootEntity data JsonConvert.DeserializeObject<YourRootEntity>(jsonStrong);

Json RestSharp deserilizing Response Data null

i use RestSharp to access a Rest API. I like to get Data back as an POCO.
My RestSharp Client looks like this:
var client = new RestClient(#"http:\\localhost:8080");
var request = new RestRequest("todos/{id}", Method.GET);
request.AddUrlSegment("id", "4");
//request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
//With enabling the next line I get an new empty object of TODO
//as Data
//client.AddHandler("*", new JsonDeserializer());
IRestResponse<ToDo> response2 = client.Execute<ToDo>(request);
ToDo td=new JsonDeserializer().Deserialize<ToDo>(response2);
var name = response2.Data.name;
my Class for the JsonObject looks like this:
public class ToDo
{
public int id;
public string created_at;
public string updated_at;
public string name;
}
and the Json Response:
{
"id":4,
"created_at":"2015-06-18 09:43:15",
"updated_at":"2015-06-18 09:43:15",
"name":"Another Random Test"
}
Per the documentation, RestSharp only deserializes to properties and you're using fields.
RestSharp uses your class as the starting point, looping through each
publicly-accessible, writable property and searching for a
corresponding element in the data returned.
You need to change your ToDo class to the following:
public class ToDo
{
public int id { get; set; }
public string created_at { get; set; }
public string updated_at { get; set; }
public string name { get; set; }
}

c# Deserialize json into List

I have this code that retrieves Json string from API link. The Json is deserialized and returned to a textbox. This works perfectly as long as there is only 1 Json value, being returned more than 1 value it crashes with this error:
Additional information: Cannot deserialize the current JSON array
(e.g. [1,2,3]) into type 'GW2_tradingPost.RootObject' because the type
requires a JSON object (e.g. {"name":"value"}) to deserialize
correctly.
To fix this error either change the JSON to a JSON object (e.g.
{"name":"value"}) or change the deserialized type to an array or a
type that implements a collection interface (e.g. ICollection, IList)
like List that can be deserialized from a JSON array.
JsonArrayAttribute can also be added to the type to force it to
deserialize from a JSON array.
Doing my research this happens because there is nowhere to deposit the Json since its not an List.
I've have tried this code and various similar ones.
List<RootObject> list = JsonConvert.DeserializeObject<List<RootObject>>(jsonReader.ToString());
return list;
This will return with error:
Error 1 Cannot implicitly convert type
'System.Collections.Generic.List' to
'GW2_tradingPost.RootObject' e:\mega\gw2_tradingpost\gw2_tradingpost\api_request.cs 34
Which i dont fully understand what it means.
Here is my full code.
api_Request.cs
public class api_Request
{
public RootObject 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);
var jsonReader = new JsonTextReader(reader);
var serializer = new JsonSerializer();
return serializer.Deserialize<RootObject>(jsonReader);
}
}
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;
}
}
}
public class Buy
{
public int listings { get; set; }
public int unit_price { get; set; }
public int quantity { get; set; }
}
public class Sell
{
public int listings { get; set; }
public int unit_price { get; set; }
public int quantity { get; set; }
}
public class RootObject
{
public int id { get; set; }
public List<Buy> buys { get; set; }
public List<Sell> sells { get; set; }
}
Form1.cs
private void button1_Click(object sender, EventArgs e)
{
RootObject RootObject = new RootObject();
api_Request api_Request = new api_Request();
richTextBox1.Text = api_Request.GetApi("https://api.guildwars2.com/v2/commerce/listings").id.ToString();
}
In this json is a single ID, so this works fine. https://api.guildwars2.com/v2/commerce/listings/19684
But when retrieving multiple ID's like here, it breaks.
https://api.guildwars2.com/v2/commerce/listings
Here is a simple solution to get listing of all id's it will a real amount of time though to go through all of them
List<RootObject> rootobject = new List<RootObject>();
using (var webclient = new WebClient())
{
var Ids = webclient.DownloadString(" https://api.guildwars2.com/v2/commerce/listings");
foreach (var id in Ids.Substring(1, s.Length-2).Split(','))
{
string url = string.Format("{0}/{1}","https://api.guildwars2.com/v2/commerce/listings",id);
var res = webclient.DownloadString(url);
var jsonObject = JsonConvert.DeserializeObject<RootObject>(res);
rootobject.Add(jsonObject);
}
}
The link that you provided for multiple ID's return an Array of Integers. I would suggest parsing this as such:
var ids = JsonConvert.DeserializeObject<int[]>(jsonReader.ToString())
As you have said, your code works for a single item, so you can use your existing code for each individual request which instead of hitting https://api.guildwars2.com/v2/commerce/listings, will be hitting https://api.guildwars2.com/v2/commerce/listings/{id} which you can use string.Format() to add where it is needed.
Seriously consider how many of the id's returned in the int[] you actually want to fetch the root object for though, as from what I can see that it returns, you will be making a hell of a lot of requests.

Deserializing JSON to List<> is not working in C#

This is the JSON i got from stream, and converted to string.
"{\"data\":[{\"thread_id\":\"1111155552222\",\"recipients\":[123123,456456],\"message_count\":2100},{\"thread_id\":\"1111155553333\",\"recipients\":[123124,456457],\"message_count\":4851},{\"thread_id\":\"1111155554444\",\"recipients\":[123125,456458],\"message_count\":435}]}"
public class DataContainer
{
List<data> data { get; set; }
}
public class data
{
public string thread_id { get; set; }
public long[] recipients { get; set; }
public int message_count { get; set; }
}
JavaScriptSerializer ser = new JavaScriptSerializer();
DataContainer data = ser.Deserialize<DataContainer>(json);
I am getting null at data, it does not seem to get deserialize. amateur in json. getting headache with this already.
Thanks!
Getting the JSON string
WebResponse response = request.GetResponse();
Stream stream = response.GetResponseStream();
Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
StreamReader reader = new StreamReader(stream, encode);
string json = reader.ReadToEnd();
It seems your "JSON you got from stream and converted to string" has been serialized twice.
ASP.NET automatically JSON serializes your service methods’ responses, even if their result is an object or collection of objects
You should be able to use it directly without having to serialize/deserialize it.
Something like:
//Assuming GetJson() returns a JSON string, which you can use directly
DataContainer data = GetJson();
Check this: http://encosia.com/asp-net-web-services-mistake-manual-json-serialization/
Also this: Reading from JSON, data not displayed

Categories