I am building C# windows form that accessing json data. I want to make it display on gridview.
How can I DeserializeObject the json data on gridview?
Sorry for newbie here.
public class Namedata
{
public string PeopleName { get; set; }
public string PeopleAge { get; set; }
public string PeopleSurname { get; set; }
}
public class SName
{
public int ResultCode { get; set; }
public string ResultName { get; set; }
public IList<Namedata> namedatas { get; set; }
}
public class Example
{
public SName s_name { get; set; }
}
public void GETJsondata()
{
string username = "myuser";
string password = "myuserpass";
byte[] byteArray = Encoding.UTF8.GetBytes("{\"name\":\"" + Name.Text + "\",\"id\":\"1\"}");
WebRequest request = WebRequest.Create("http://myservice/Service4.svc/s_name");
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)));
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream = request.GetResponse().GetResponseStream();
var result = (new StreamReader(stream).ReadLine());
JsonConvert.DeserializeObject<Example>(result);
ultragridiew1.DataSource = result;
}
here are json data:
{
"s_name": {
"ResultCode": 1,
"ResultName": "Found",
"namedatas": [
{
"PeopleName": "Jane",
"PeopleAge": "20",
"PeopleSurname": "Jade"
},
{
"PeopleName": "Newton",
"PeopleAge": "18",
"PeopleSurname": "Handy"
},
{
"PeopleName": "Java",
"PeopleAge": "21",
"PeopleSurname": "Handy"
}
]
}
}
You are not giving the gridview the correct source. Try this,
var data = JsonConvert.DeserializeObject<Example>(result);
ultragridiew1.DataSource = data.s_name.namedatas;
Base on the information, here is a potential solution:
public class Namedata
{
public string PeopleName { get; set; }
public string PeopleAge { get; set; }
public string PeopleSurname { get; set; }
}
public class SName
{
public int ResultCode { get; set; }
public string ResultName { get; set; }
public Namedata[] namedatas { get; set; }
}
public class Example
{
public SName s_name { get; set; }
}
public void GETJsondata()
{
HttpClient _client = new HttpClient();
string username = "myuser";
string password = "myuserpass";
var byteArray = System.Text.Encoding.ASCII.GetBytes($"{username}:{password}");
_client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(byteArray));
dynamic content = new ExpandoObject();
content.name = Name.Text;
content.id = 1;
var json = Newtonsoft.Json.JsonConvert.SerializeObject(content);
var data = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = _client.PostAsync("http://myservice/Service4.svc/s_name", data).Result;
var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Example>(response.Content.ReadAsStringAsync().Result);
ultragridiew1.DataSource = data.s_name.namedatas;
}
Main change I have done is to use HttpClient. It removes a lot of boilerplate code that is required with webrequest.
#Chetan Ranpariya had correct me. Thank you
public class Namedata
{
public string PeopleName { get; set; }
public string PeopleAge { get; set; }
public string PeopleSurname { get; set; }
}
public class SName
{
public int ResultCode { get; set; }
public string ResultName { get; set; }
public IList<Namedata> namedatas { get; set; }
}
public class Example
{
public SName s_name { get; set; }
}
public void GETJsondata()
{
string username = "myuser";
string password = "myuserpass";
byte[] byteArray = Encoding.UTF8.GetBytes("{\"name\":\"" + Name.Text + "\",\"id\":\"1\"}");
WebRequest request = WebRequest.Create("http://myservice/Service4.svc/s_name");
request.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password)));
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = byteArray.Length;
Stream stream = request.GetRequestStream();
stream.Write(byteArray, 0, byteArray.Length);
stream = request.GetResponse().GetResponseStream();
var result = (new StreamReader(stream).ReadLine());
var exampleObj = JsonConvert.DeserializeObject<Example>(result);
ultragridiew1.DataSource = exampleObj.s_name.namedatas
}
Related
I want to post data to the database where I am fetching the data in a JSON format.
Here is the following JSON string:
"[{"cph_id":"67/123/7894","phone_no":"0000623019"},
{"cph_id":"69/213/1234","phone_no":"0000623019"}]"
I have also created the following classes:
public class RootObject
{
public List<dlregistrationdata> data { get; set; }
}
public class dlregistrationdata
{
public string cph_id[] { get; set; }
public string phone_no[] { get; set; }
}
I try to deserialize using the following command:
try
{
var obj = JsonConvert.DeserializeObject<List<dlregistrationdata>>(result);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://172.61.25.30/CPRestApi/api/user/register");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (email != null)
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
dynamic arr = new JObject();
for (int i = 0; i < obj.Count; i++)
{
arr.cph_id = obj[i].cph_id;
arr.user_name = email;
arr.user_phone_number = obj[i].phone_no;
arr.user_password = password;
arr.status = 1;
arr.name = name;
}
streamWriter.Write(arr);
}
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
if (httpResponse.StatusCode == System.Net.HttpStatusCode.Created)
{
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result1 = streamReader.ReadToEnd();
}
return RedirectToLocal("Index");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
ViewBag.ErrorMessage = "User Already Registered";
ModelState.AddModelError("", "User Already Registered");
return View(model);
}
But I am getting the error:
"converting value "67/123/7894" to type 'System.String[]'. Path '[0].cph_id', line 1, position 24"
Any help will be highly appreciated.
Thank You!
Changes made in model class:
public class dlregistrationdata
{
public string cph_id { get; set; }
public string phone_no { get; set; }
}
public class RequestRegistrationAPI {
public string user_name { get; set; }
public string user_password { get; set; }
public string user_phone_number { get; set; }
public string name { get; set; }
public int status { get; set; }
public string[] cph_id { get; set; }
}
Changes made in code:
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
List<string> cphid = new List<string>();
string phone_no = "";
foreach (dlregistrationdata data in obj)
{
cphid.Add(data.cph_id);
phone_no = data.phone_no;
}
RequestRegistrationAPI request = new RequestRegistrationAPI();
request.user_name = email;
request.user_password = password;
request.user_phone_number = phone_no;
request.name = name;
request.cph_id = cphid.ToArray();
request.status = 1;
streamWriter.Write(JsonConvert.SerializeObject(request));
}
This works perfectly for me.
change classes to :
public class dlregistrationdata
{
public string cph_id { get; set; }
public string phone_no { get; set; }
}
now change code to :
var obj = JsonConvert.DeserializeObject<List<dlregistrationdata>>(result);
var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://172.61.25.30/CPRestApi/api/user/register");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
if (email != null)
{
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
dynamic arr = new JObject();
for (int i = 0; i < obj.Count; i++)
{
arr.cph_id = obj[i].cph_id;
arr.user_name = email;
arr.user_phone_number = obj[i].phone_no;
arr.user_password = password;
arr.status = 1;
arr.name = name;
}
streamWriter.Write(arr);
}
}
I have xamarin.forms app in which I am trying to consume an API. I can get the results but cant deserialize the data. It says "Childern could not be evaluated"
My Json data
{
"success": true,
"user": {
"auth_uuid": "52320",
"current_store": 9,
"permissions": {
"write_notifications": true,
},
"has_accepted_mobile_one_terms": false,
"store": {
"id": 9,
"name": "South Street",
"number": "0009",
}
},
"message": "User Logged In",
"sidebarItems": [
{
"id": 53,
"name": "Notification Center",
}
],
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9"
}
My Corresponding C# class
public clas loginData
{
public class Permissions
{
public bool write_notifications { get; set; }
}
public class Store
{
public int id { get; set; }
public string name { get; set; }
public string number { get; set; }
}
public class User
{
public string auth_uuid { get; set; }
public int current_store { get; set; }
public Permissions permissions { get; set; }
public bool has_accepted_mobile_one_terms { get; set; }
public Store store { get; set; }
}
public class SidebarItem
{
public int id { get; set; }
public string name { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public User user { get; set; }
public string message { get; set; }
public List<SidebarItem> sidebarItems { get; set; }
public string token { get; set; }
}
}
My common class for making API call
public class APICall
{
Uri baseAddress = new Uri(CommonValues.BaseURL);
string apiurl;
string postdata;
public ErrorMessageData errorMessage;
public APICall(string apiurl, string postdata)
{
this.apiurl = apiurl;
this.postdata = postdata;
this.loadingIndicator = loadingIndicator;
errorMessage = null;
}
public T APICallResult<T>()
{
try
{
var client = new HttpClient { BaseAddress = baseAddress };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var req = new HttpRequestMessage(HttpMethod.Post, apiurl);
req.Content = new StringContent(postdata, Encoding.UTF8, "application/json");
string stringObtained = "";
Task<string> task = Task.Run(async () => await Threading(client, req));
task.Wait();
stringObtained = task.Result;
var jsonObtained = Regex.Unescape(stringObtained);
var resultJSON = '[' + jsonObtained + ']';
T resultObject;//Generic type object
try
{
resultObject = JsonConvert.DeserializeObject<T>(resultJSON);
return resultObject;
}
catch (Exception)
{
List<ErrorMessageData> errorMessages = JsonConvert.DeserializeObject<List<ErrorMessageData>>(resultJSON);
errorMessage = errorMessages[0];
return default(T);
}
}
catch (Exception e)
{
errorMessage = new ErrorMessageData();
errorMessage.Flag = false;
errorMessage.Message = e.Message;
return default(T);
}
}
async Task<string> Threading(HttpClient client, HttpRequestMessage req)
{
var resp = await client.SendAsync(req);
resp.EnsureSuccessStatusCode();
string stringObtained = await resp.Content.ReadAsStringAsync();
return stringObtained;
}
}
How I am making API call
ObservableCollection<loginData> AuthDataObj;
string postdataForAuth = "{\"email\":\"" + "sample#sam.com" + "\",\"password\":\"" + "1234" + "\"}";
NCAPICall callForAuth = new APICall("/auth/login", postdataForAuth, null);
try
{
AuthDataObj = callForAuth.APICallResult<ObservableCollection<loginData>>();
}
catch (Exception ex)
{
await DisplayAlert("Error", ex.Message, "ok");
}
How to solve this issue? Is this something related to mapping of data to my model class?Any help is appriciated.
You need to use RootObject for the deserialization.
Change this line of code
var AuthDataObj = callForAuth.APICallResult<ObservableCollection<RootObject>>();
I want to get all variables from https://api.coinmarketcap.com/v1/ticker/ in my c# console application.
How can I do this?
I started with getting the whole page as a stream. What to do now?
private static void start_get()
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create
(string.Format("https://api.coinmarketcap.com/v1/ticker/"));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
Stream Answer = WebResp.GetResponseStream();
StreamReader _Answer = new StreamReader(Answer);
Console.WriteLine(_Answer.ReadToEnd());
}
First you need a custom class to use for deserialization:
public class Item
{
public string id { get; set; }
public string name { get; set; }
public string symbol { get; set; }
public string rank { get; set; }
public string price_usd { get; set; }
[JsonProperty(PropertyName = "24h_volume_usd")] //since in c# variable names cannot begin with a number, you will need to use an alternate name to deserialize
public string volume_usd_24h { get; set; }
public string market_cap_usd { get; set; }
public string available_supply { get; set; }
public string total_supply { get; set; }
public string percent_change_1h { get; set; }
public string percent_change_24h { get; set; }
public string percent_change_7d { get; set; }
public string last_updated { get; set; }
}
Next, you can use Newtonsoft Json, a free JSON serialization and deserialization framework in the following way to get your items (include the following using statements):
using System.Net;
using System.IO;
using Newtonsoft.Json;
private static void start_get()
{
HttpWebRequest WebReq = (HttpWebRequest)WebRequest.Create(string.Format("https://api.coinmarketcap.com/v1/ticker/"));
WebReq.Method = "GET";
HttpWebResponse WebResp = (HttpWebResponse)WebReq.GetResponse();
Console.WriteLine(WebResp.StatusCode);
Console.WriteLine(WebResp.Server);
string jsonString;
using (Stream stream = WebResp.GetResponseStream()) //modified from your code since the using statement disposes the stream automatically when done
{
StreamReader reader = new StreamReader(stream, System.Text.Encoding.UTF8);
jsonString = reader.ReadToEnd();
}
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(jsonString);
Console.WriteLine(items.Count); //returns 921, the number of items on that page
}
Finally, the list of elements is stored in items.
A simplified version of Keyur PATEL's work.
static void GetCoinValues()
{
string json = new WebClient().DownloadString("https://api.coinmarketcap.com/v1/ticker/");
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
foreach (var item in items)
{
Console.WriteLine("ID: " + item.id.ToUpper());
Console.WriteLine("Name: " + item.name.ToUpper());
Console.WriteLine("Symbol: " + item.symbol.ToUpper());
Console.WriteLine("Rank: " + item.rank.ToUpper());
Console.WriteLine("Price (USD): " + item.price_usd.ToUpper());
Console.WriteLine("\n");
}
}
I have a Api link that returns this Json structure. In the code I request this Api link and then deserialize it into a list. This is done without problems. But if the Api returns more than 50 "counts" it creates another page. How do i get around to loop through all pages and add everything to the existing list?
In the case i linked there will be 38 pages. All need to be added to the list.
Call
// spidyApiUrl = http://www.gw2spidy.com/api/v0.9/json/item-search/iron/1
var spidyApi_idByName_result = api_Handler.objFromApi_idToName(spidyApiUrl);
Function with the return
public RootObject objFromApi_idToName(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
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);
RootObject rootObject = serializer.Deserialize<RootObject>(jsonReader);
if (rootObject.count > 0) { return rootObject; }
else { return null; }
}
}
And ofcourse i also have the get; set; classes.
How do I loop through all pages (if mutliple pages exist, which doesnt have to) and add these to the same object list.
You need continue downloading the data until page == last_page
As you get each page of data you then add the new set of results to the original rootObject's results property with AddRange
I also changed the url that gets passed into the function from
http://www.gw2spidy.com/api/v0.9/json/item-search/iron/1
to
http://www.gw2spidy.com/api/v0.9/json/item-search/iron
This allows me to add the page numbers to the url to get all the pages
http://www.gw2spidy.com/api/v0.9/json/item-search/iron/1
http://www.gw2spidy.com/api/v0.9/json/item-search/iron/2
.....
http://www.gw2spidy.com/api/v0.9/json/item-search/iron/38
Code:
public class Result
{
public int data_id { get; set; }
public string name { get; set; }
public int rarity { get; set; }
public int restriction_level { get; set; }
public string img { get; set; }
public int type_id { get; set; }
public int sub_type_id { get; set; }
public string price_last_changed { get; set; }
public int max_offer_unit_price { get; set; }
public int min_sale_unit_price { get; set; }
public int offer_availability { get; set; }
public int sale_availability { get; set; }
public int sale_price_change_last_hour { get; set; }
public int offer_price_change_last_hour { get; set; }
}
public class RootObject
{
public int count { get; set; }
public int page { get; set; }
public int last_page { get; set; }
public int total { get; set; }
public List<Result> results { get; set; }
}
class Program
{
static void Main(string[] args)
{
objFromApi_idToName("http://www.gw2spidy.com/api/v0.9/json/item-search/iron");
}
public static RootObject objFromApi_idToName(string url)
{
RootObject rootObject = null;
RootObject tempRootObject = null;
int page = 1;
do
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url + "/" + page);
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);
tempRootObject = serializer.Deserialize<RootObject>(jsonReader);
if (rootObject == null)
{
rootObject = tempRootObject;
}
else
{
rootObject.results.AddRange(tempRootObject.results);
rootObject.count += tempRootObject.count;
}
}
page++;
} while (tempRootObject != null && tempRootObject.last_page != tempRootObject.page);
return rootObject;
}
}
Are you using Web API? If so, could you try something like this?
public RootObject objFromApi_idToName(string url)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("<your uri here>");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync("<uri extention here>");
if (response.IsSuccessStatusCode)
{
string jsonStr = await response.Content.ReadAsStringAsync();
var deserializedResponse = JsonConvert.DeserializeObject<List<your model class here>>(jsonStr);
return deserializedResponse;
}
}
My C# class
public class City
{
public int City_id { get; set; }
public string City_name { get; set; }
}
public class Model
{
public City[] lstCitiesResult { get; set; }
}
Web Request
string url = "my url";
WebRequest request = WebRequest.Create(url);
// provide your ID And Password for proxy
request.Proxy.Credentials = new NetworkCredential(XXXX);
WebResponse ws = request.GetResponse();
DataContractJsonSerializer jsonSerializer =
new DataContractJsonSerializer(typeof(List<Model>));
List<Model> dataList =
(List<Model>)jsonSerializer.ReadObject(ws.GetResponseStream());
string result = "";
foreach (var data1 in dataList)
{
result = result + data1.lstCitiesResult.ToString();
}
TextBox1.Text = result.ToString();
My error: I got null in datalist...what i do?