How to return WebRequest Multidimensional JSON? - c#

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

Related

Map WebReponse to Model Class

I have a service that is posting data to a URL and listening for the response.
This is the service call
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = null;
response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, encode, true);
string strResponse = reader.ReadToEnd();
The string response that it's returning is
"{"TransactionConfirmationWrapedResult":"{\"ResultCode\":\"1\",\"ResultDesc\":\"Failed -\",\"ThirdPartyTransID\":\"\"}"}"
I would like to map this result to class like this;
public class M2PDto
{
[DataMember(Name = "TransactionConfirmationWrapedResult")]
public M2P2Dto WrapedResult { get; set; }
}
public class M2P2Dto
{
[DataMember(Name = "ResultCode")]
public string ResultCode { get; set; }
[DataMember(Name = "ResultDesc")]
public string ResultDesc { get; set; }
[DataMember(Name = "ThirdPartyTransID")]
public string ThirdPartyTransID { get; set; }
}
This is my deserializing code
M2PDto m2P = JsonConvert.DeserializeObject<M2PDto>(strResponse);
I can't seem to figure out how to deserialize it, keeps failing by passing null to m2P

C# issue calling EORI SOAP Service

I am trying to call the EORI validation open interface from within a C# application but am not getting anywhere.
I've looked around the site and there doesn't seem to be any documentation on how to do this.
Site: http://ec.europa.eu/taxation_customs/dds2/eos/news/newstar.jsp?Lang=en
WSDL: http://ec.europa.eu/taxation_customs/dds2/eos/validation/services/validation?wsdl
I've created a new C# Console App and added the WSDL as a service reference then tried calling the service but get the following exception...
System.ServiceModel.CommunicationException: 'The server did not
provide a meaningful reply; this might be caused by a contract
mismatch, a premature session shutdown or an internal server error.'
I've used the online tool with the number and it returns data as expected
http://ec.europa.eu/taxation_customs/dds2/eos/eori_validation.jsp?Lang=en
Has anybody else had any luck with this?
Thanks
Thanks for the help, In case anyone else was struggling, below is the helper class for making and sending the request.
public class EoriModel
{
string _url;
public EoriModel()
{
_url = "http://ec.europa.eu/taxation_customs/dds2/eos/validation/services/validation";
}
public EoriResponseModel ValidateEoriNumber(string number)
{
if (number == null)
{
return null;
}
XmlDocument soapEnvelopeXml = CreateSoapEnvelope(number);
HttpWebRequest webRequest = CreateWebRequest(_url);
InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);
IAsyncResult asyncResult = webRequest.BeginGetResponse(null, null);
asyncResult.AsyncWaitHandle.WaitOne();
string response;
using (WebResponse webResponse = webRequest.EndGetResponse(asyncResult))
{
using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
{
response = rd.ReadToEnd();
}
}
int startPos = response.IndexOf("<return>");
int lastPos = response.LastIndexOf("</return>") - startPos + 9;
string responseFormatted = response.Substring(startPos, lastPos);
XmlSerializer serializer = new XmlSerializer(typeof(EoriResponseModel));
EoriResponseModel result;
using (TextReader reader = new StringReader(responseFormatted))
{
result = (EoriResponseModel)serializer.Deserialize(reader);
}
return result;
}
private static HttpWebRequest CreateWebRequest(string url)
{
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.ContentType = "text/xml;charset=\"utf-8\"";
webRequest.Accept = "text/xml";
webRequest.Method = "POST";
return webRequest;
}
private static XmlDocument CreateSoapEnvelope(string number)
{
XmlDocument soapEnvelopeDocument = new XmlDocument();
StringBuilder xmlBuilder = new StringBuilder();
xmlBuilder.AppendFormat("<soap:Envelope xmlns:soap={0} >", "'http://schemas.xmlsoap.org/soap/envelope/'");
xmlBuilder.Append("<soap:Body>");
xmlBuilder.AppendFormat("<ev:validateEORI xmlns:ev={0} >", "'http://eori.ws.eos.dds.s/'");
xmlBuilder.AppendFormat("<ev:eori>{0}</ev:eori>", number);
xmlBuilder.Append("</ev:validateEORI>");
xmlBuilder.Append("</soap:Body> ");
xmlBuilder.Append("</soap:Envelope> ");
soapEnvelopeDocument.LoadXml(xmlBuilder.ToString());
return soapEnvelopeDocument;
}
private static void InsertSoapEnvelopeIntoWebRequest(XmlDocument soapEnvelopeXml, HttpWebRequest webRequest)
{
using (Stream stream = webRequest.GetRequestStream())
{
soapEnvelopeXml.Save(stream);
}
}
}
And the class with annotation used to parse the results
[XmlRoot(ElementName = "return")]
public class EoriResponseModel
{
[XmlElement(ElementName = "requestDate")]
public string RequestDate { get; set; }
[XmlElement(ElementName = "result")]
public List<Result> Result { get; set; }
}
[XmlRoot(ElementName = "result")]
public class Result
{
[XmlElement(ElementName = "eori")]
public string Eori { get; set; }
[XmlElement(ElementName = "status")]
public string Status { get; set; }
[XmlElement(ElementName = "statusDescr")]
public string StatusDescr { get; set; }
[XmlElement(ElementName = "name")]
public string Name { get; set; }
[XmlElement(ElementName = "street")]
public string Street { get; set; }
[XmlElement(ElementName = "postalCode")]
public string PostalCode { get; set; }
[XmlElement(ElementName = "city")]
public string City { get; set; }
[XmlElement(ElementName = "country")]
public string Country { get; set; }
}
If you Google the URI that is deep in the Reference.cs file that opens if you open the definition of the EORI validation methods, then you'll that someone on this page here https://www.codeproject.com/Questions/1075553/Soap-Message-Format-Issue-while-accessing-webservi is having the same issue.
On that page he quotes this sample code that he is using to make a query.
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<ev:validateEORI xmlns:ev="http://eori.ws.eos.dds.s/">
<ev:eori>DE123456</ev:eori>
<ev:eori>IT123456789</ev:eori>
</ev:validateEORI>
</soap:Body>
</soap:Envelope>
Try this code in Postman, and enjoy the results. :D
His query is ultimately that the C# code he wrote isn't creating valid XML, but at least this XML will get you results from the API for your testing / development process to proceed.

c# deserialize mutliple Json into same list

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;
}
}

JsonConvert.PopulateObject - Returns empty object

The following bit of code attempts to read some json and populate an object:
public Response ParseObject(string Json)
{
Response response = new Response();
JsonConvert.PopulateObject(Json, response);
return response;
}
Here's the Response object:
public class Response
{
public string id { get; set; }
public string name { get; set; }
public string description { get; set; }
public string status { get; set; }
public string incorporationDate { get; set; }
public string latestAnnualReturnDate { get; set; }
public string latestAccountsDate { get; set; }
public string companyType { get; set; }
public string accountsType { get; set; }
Unfortunately, the object (response) is empty ie (response.id is null as are all of the other properties).
I'm guessing that I need to pass in some JsonSerializerSettings but I can't find a tutorial anywhere?
You might want to check your Json string. When I run your code with the below set-up I get the values in the Response object.
var s = "{ \"id\":\"2\" , \"name\":\"Doe\" }";
Response response = ParseObject(s);
Response Try to use the above. This is to get the string from HttpContext
Stream dataStream = context.Request.InputStream;
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Response data =(Response )json_serializer.DeserializeObject(responseFromServer);
In your case you can use
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
Response data =(Response )json_serializer.DeserializeObject(Json);

Web HttpRequest method in asp.net

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?

Categories

Resources