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?
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 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
}
this is my current code:
public string Get(int id)
{
HttpRequestCachePolicy policy = new HttpRequestCachePolicy(HttpRequestCacheLevel.Default);
HttpWebRequest.DefaultCachePolicy = policy;
HttpRequestCachePolicy noCachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("some URl that returns a json");
request.Method = WebRequestMethods.Http.Get;
request.Accept = "application/json";
request.ContentType = "application/json; charset=utf-8";
request.MaximumAutomaticRedirections = 4;
request.MaximumResponseHeadersLength = 4;
request.Credentials = CredentialCache.DefaultCredentials;
request.CachePolicy = noCachePolicy;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
return // RESPONSE AS JSON???;
}
public class Persons
{
public string index { get; set; }
public string thing { get; set; }
public string name { get; set; }
public string title { get; set; }
}
I want to return the response as multidimensional json..
How can i do that?
It should look like this:
{"data":{"Person1":{"id":1,"thing":"thingOne","name":"personOneName","title":"personOneTitle"},"Person2":{"id":2,"thing":"thingTwo","name":"personTwoName","title":"personTwoTitle"}}
Be sure to add the directive below to your class
using Newtonsoft.Json;
This code will turn your response into an object.
Stream newStream = response .GetResponseStream();
StreamReader sr = new StreamReader(newStream);
var result = sr.ReadToEnd();
//this will turn your response into a c# object of RootObject Type
//only do this is you're sure it will Deserialize into a RootObject type.
var convertResponseToObj= JsonConvert.DeserializeObject<RootObject>(result);
//if you want to see what's being returned by your endpoint
//without turning it into a RootObject type then remove <RootObject> see line below.
//doing this may help you Deserialize the response correctly.
//var convertResponseToObj= JsonConvert.DeserializeObject(result);
public class Persons
{
public string index { get; set; }
public string thing { get; set; }
public string name { get; set; }
public string title { get; set; }
}
public class RootObject
{
public List<Person> data {get; set;}
}
If you want to do some manipulations to that c# object and then turn it into JSON you can can do this:
string myJson = JsonConvert.SerializeObject(someCSharpObj); //this will turn your c# object into json
I have a WPF application that calls an API and creates an System.Xml.Linq.XDocument using XDocument.Parse(string). I am running into a problem where an XmlException ("Root element is missing") is thrown when I try to do this, but my XML is completely valid. I tried syntax-checking it by calling the API in my browser and checking its syntax, calling the API in my application and Console.WriteLineing the response, and using various XML syntax validators (all of which returned no errors).
A sample XML response from the API is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<response>
<event title="Event 1" id="75823347" icon="www.example.com/images/event1-icon.png" uri="www.example.com/rsvp/event1" mode="none" price="10.00" cover="www.example.com/event1-cover.png" enddate="2016-06-01 14:00:00" startdate="2016-06-01 12:00:00" address="1 Example St, Example City State 12345" location="Example Place" description="This is an event" shortdescription="This is an event" theme="auto" color="#FF000000"/>
</response>
This is my application's code:
public static WebRequest CreateRequest(string baseUrl, string httpMethod, Dictionary<string, string> requestValues) {
var requestItems = requestValues == null ? null : requestValues.Select(pair => string.Format("&{0}={1}", pair.Key, pair.Value));
var requestString = "";
if (requestItems != null)
foreach (var s in requestItems)
requestString += s;
var request = WebRequest.CreateHttp(baseUrl + CredentialRequestString + requestString);
request.Method = httpMethod.ToUpper();
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = CredentialCache.DefaultCredentials;
return request;
}
public static WebRequest CreateRequest(string apiEndpoint, string endpointParam, int apiVersion, string httpMethod, Dictionary<string, string> requestValues) {
return CreateRequest(string.Format("http://www.example.com/api/v{0}/{1}/{2}", apiVersion, apiEndpoint, endpointParam), httpMethod, requestValues);
}
public static async Task<string> GetResponseFromServer(WebRequest request) {
string s;
using (var response = await request.GetResponseAsync()) {
using (var responseStream = response.GetResponseStream()) {
using (var streamReader = new StreamReader(responseStream)) {
s = streamReader.ReadToEnd();
}
}
}
return s;
}
public static async Task<List<Event>> GetEvents() {
var response = await GetResponseFromServer(CreateRequest("events", "", 1, "GET", null));
Console.WriteLine(response); //validation
var data = XDocument.Parse(response).Root; //XmlException: Root element is mising
return new List<Event>(data.Elements("event").Select(e => Event.FromXml(e.Value)));
}
Why is this happening?
The following code works
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
var data = XDocument.Load(FILENAME);
Event _event = Event.FromXml(data.Descendants("event").FirstOrDefault());
}
}
public class Event
{
public string title { get ; set; }
public string icon {get; set; }
public string uri { get; set; }
public string mode { get;set; }
public decimal price { get; set; }
public string cover { get; set; }
public DateTime enddate { get; set; }
public DateTime startdate { get; set; }
public string address { get; set; }
public string location { get; set; }
public string description { get; set; }
public string shortdescription { get; set; }
public string theme { get; set; }
public uint color { get; set; }
public static Event FromXml(XElement data)
{
Event _event = new Event();
_event.title = (string)data.Attribute("title");
_event.icon = (string)data.Attribute("icon");
_event.uri = (string)data.Attribute("uri");
_event.mode = (string)data.Attribute("mode");
_event.price = (decimal)data.Attribute("price");
_event.cover = (string)data.Attribute("cover");
_event.enddate = (DateTime)data.Attribute("enddate");
_event.startdate = (DateTime)data.Attribute("startdate");
_event.address = (string)data.Attribute("address");
_event.location = (string)data.Attribute("location");
_event.description = (string)data.Attribute("description");
_event.shortdescription = (string)data.Attribute("shortdescription");
_event.theme = (string)data.Attribute("theme");
_event.color = uint.Parse(data.Attribute("color").Value.Substring(1), System.Globalization.NumberStyles.HexNumber) ;
return _event;
}
}
}
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;
}
}