Parsing Json response from Httpwebrequest - c#

I'm trying to parse data from a response using httpwebrequest, which is in JSON format, I've tried to use JSON.Net but seem to be having no luck, I'm open to using Regex if need be.
Example of current code -
var request = (HttpWebRequest)WebRequest.Create("https://www.example.com/response");
request.Method = "GET";
request.Accept = "application/json";
request.ContentType = "application/json; charset=utf-8;"
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
dynamic data = JOBject.Parse(response);
Console.WriteLine(data.name);
Example of response in full -
[{"_id":"hello","_source":{"name":"hello","example":"hey"},"_type":"_doc"}]

Try This:
WebRequest webRequest = WebRequest.Create("https://www.example.com/response");
HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
if (response.StatusDescription == "OK")
{
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
// Display the content.
dynamic data = JObject.Parse(responseFromServer);
Console.Write(data.name);
}

You can create these two classes like this.
public class Source
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("example")]
public string Example { get; set; }
}
public class ResponseObject
{
[JsonProperty("_id")]
public string Id { get; set; }
[JsonProperty("_source")]
public Source Source { get; set; }
[JsonProperty("_type")]
public string Type { get; set; }
}
And then parse your response like this
var data = JsonConvert.DeserializeObject<ResponseObject>(response);
Hope this will help you

Related

Put a part of a POST request in variable

I did a POST request code pointing to an API to do an automatic exchange program.
Here is the code:
string webAddr = "https://shapeshift.io/shift";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"withdrawal\" : \"***ADDRESS WITH LETTER AND NUMBER***\", \"pair\" : \"eth_xmr\" }";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
}
And after executing the code, I'm getting this in the console
{"orderId":"1f90346c-c6d4-4d89-a24c-78b2bbdb6292","deposit":"0x534aa684274b4711f65b2d0e2e403cb169201255","depositType":"ETH","withdrawal":"***ADDRESS WITH LETTER AND NUMBER***","withdrawalType":"XMR"
Now, I want to put the address from deposit that I'm getting from the API into a string variable. I tried some code but I can't make it working. So how can I put this address in a string variable ?
You could deserialize the response and get from there that you want. In order to do so you could define a class, let's name it ApiResponse:
public class ApiResponse
{
[JsonProperty("orderId")]
public string orderId { get; set; }
[JsonProperty("deposit")]
public string deposit { get; set; }
[JsonProperty("depositType")]
public string depositType { get; set; }
[JsonProperty("withdrawal")]
public string withdrawal { get; set; }
[JsonProperty("withdrawalType")]
public string withdrawalType { get; set; }
}
and then after
var responseText = streamReader.ReadToEnd();
make the deserialization:
var apiResponse = JsonConvert.DeserializeObject<ApiResponse>(responseText);
I have used the Json.NET library. So if you haven't isntall it, you should do so or you could make use of another library and change correspondingly the above code.

How to parse Json WebApi response containing C# list

hi I have a json response like
{"Status":"Success","Message":"Authentication
successful","Data":{"Key":"sdsdIRs99Iebe6QHmawlBsCks9mqfUt6jKYNQ%2bW","UserId":"ddjjj8-11e6-637af7"}}
how can I parse this to read response.
I am doing this way:
private void POST(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
postData="{\"UserName\": \"abc\"," +"\"Password\": \"mypwd\"}";
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/x-www-form-urlencoded";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
using (var reader = new StreamReader(response.GetResponseStream()))
{
JavaScriptSerializer js = new JavaScriptSerializer();
var objText = reader.ReadToEnd();
string str= objText;
MyObject myojb = (MyObject)js.Deserialize(objText,typeof(MyObject));
}
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}
I am able to read "Status" and "Message" but unable to read "Key" and "UserID" values.
Please help!
You can use Newtonsoft Json instead of JavaScriptSerializer the class structure for your json looks like this
public class Rootobject
{
public string Status { get; set; }
public string Message { get; set; }
public Data Data { get; set; }
}
public class Data
{
public string Key { get; set; }
public string UserId { get; set; }
}
Deserialization could be done easily like
Rootobject ro = JsonConvert.DeserializeObject<Rootobject>(json);
Console.WriteLine(ro.Status + ", " + ro.Message + ", " + ro.Data.Key + ", " + ro.Data.UserId);
Guessing (since we don't know the structure of the MyObject class) how you access your data:
String status = myobj.status;
String message = myobj.message;
Now since the other data properties are in the "data" node of your json, you should be able to access them like this:
String key = myobj.data.key;
String userId = myobj.data.userId;

c# json json.net parse to class

For some time I have a problem with the code.
Trying to retrieve data from the API using the json but when trying to parse json and send it to the class I receives empty string.
The json data looks like this
{"Wynik":{"Token":"String","DataCzasWaznosci":"\/Date(-62135596800000-0000)\/"}
... and this is my code:
public void post()
{
Autoryzacja_zaloguj a_zaloguj = new Autoryzacja_zaloguj();
string url = a_zaloguj.Link;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
byte[] requestBytes = System.Text.Encoding.ASCII.GetBytes(a_zaloguj.Json);
req.Method = "POST";
req.ContentType = "application/json";
req.ContentLength = requestBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(requestBytes, 0, requestBytes.Length);
requestStream.Close();
HttpWebResponse res = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(res.GetResponseStream(), System.Text.Encoding.Default);
string backstr = sr.ReadToEnd();
dynamic d = JObject.Parse(backstr);
var wynik = d.Wynik;
string token = wynik.Token;
DateTime data = wynik.DataCzasWaznosci;
Wyniki wyniki = new Wyniki();
wyniki.test = token;
sr.Close();
res.Close();
}
public class Wyniki
{
public string test { get; internal set; }
}
You could use Newtosoft nugget package for this kind of parsing
http://www.newtonsoft.com/json
public class Wynik
{
public string Token { get; set; }
public DateTime DataCzasWaznosci { get; set; }
}
/*Deserialization part */
string backstr = sr.ReadToEnd();
Wynikm = JsonConvert.DeserializeObject<Wynik>(backstr);

XmlSerializer WebResponse

I have this XML with many names, like a list:
<apelidos>
<apelido>Casmilo</apelido>
<apelido>Castro</apelido>
</apelidos>
And I did my model like this:
namespace IdCel.Model
{
[XmlTypeAttribute(AnonymousType = true)]
public class apelidos
{
[XmlArray("apelidos")]
[XmlArrayItem("apelidos")]
public List<apelido> apelidosNomes { get; set; }
public apelidos()
{
apelidosNomes = new List<apelido>();
}
}
public class apelido
{
[XmlElement(ElementName = "apelido")]
public string apelidoNome { get; set; }
}
}
And my XmlSerializer
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
XmlSerializer ser = new XmlSerializer(objetoLista.GetType());
WebResponse response = request.GetResponse();
var result = ser.Deserialize(response.GetResponseStream());
return result;
But it's not working, I do the same code with XML without list and it's working fine
If you just have to read the contents of the apelido tags, you are much faster when you are using Linq To XML. For example:
var xml = #"<apelidos>
<apelido>Casmilo</apelido>
<apelido>Castro</apelido>
</apelidos>";
var doc = XDocument.Parse(xml);
var apelidos = from apelido in doc.Descendants("apelido")
select apelido.Value;
This gives you an IEnumerable<string> as result containing all the names.
EDIT: To load the XML from the web you can do the following:
HttpWebRequest request = WebRequest.Create(uri) as HttpWebRequest;
WebResponse response = request.GetResponse();
var doc = XDocument.Load(response.GetResponseStream());
Now It's worked!
I did this:
[Serializable()]
public class apelidos
{
[System.Xml.Serialization.XmlElement("apelido")]
public List<string> apelido { get; set; }
}
And this:
HttpWebRequest request = WebRequest.Create(uri)
as HttpWebRequest;
XmlSerializer ser = new XmlSerializer(objetoLista.GetType());
WebResponse response = request.GetResponse();
var result = ser.Deserialize(response.GetResponseStream());
return result;

Sending list of objects to Web API

I am having trouble sending a list of objects to a webapi controller.
This is the controler:
[AcceptVerbs("POST")]
public string syncFoodData(List<intakeSync> str)
{
string apikey = Request.Headers.GetValues("api_key").ToArray()[0];
return "data syncronised";
}
This is the class:
public class intakeSync
{
public int memberID { get; set; }
public Double size { get; set; }
public string food { get; set; }
public string token { get; set; }
public string time { get; set; }
public string date { get; set; }
public string nocatch { get; set; }
public string calories { get; set; }
}
The value of str is always null.
this is the webmethod that sends the httprequest to the webapi
public static string syncIntakeData(string token, string[] syncString)
{
JavaScriptSerializer js = new JavaScriptSerializer();
List<intakeSync> str = new List<intakeSync>();
for (int i = 0; i <= syncString.Length - 1; i++)
{
str.Add(js.Deserialize<intakeSync>(syncString[i]));
}
string url = URI + "/api/Food/?str=" +js.Serialize(str);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.Headers.Add("api_key", token);
Stream requestStream = request.GetRequestStream();
StreamReader read = new StreamReader(request.GetResponse().GetResponseStream());
string dat = read.ReadToEnd();
read.Close();
request.GetResponse().Close();
return dat;
}
You can use this :
Request body in Json
[{id:1, nombre:"kres"},
{id:2, nombre:"cruz"}]
Api Rest .net C#
public string myFunction(IEnumerable<EntitySomething> myObj)
{
//...
return "response";
}
I don't know really how your JSON is serialized in the line js.Serialize(str); I suspect that this line is the core problem. Sending JSON is better suited in the POST Request body than in the query string. Anyways, I think that HttpClient is better suited for working with WebApi because it offers symmetric programming experience. You could try something like that with HttpClient :
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(URI);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("api_key", token);
var content = new ObjectContent(syncString, new JsonMediaTypeFormatter());
var result = client.PostAsync("/api/Food/", content).Result;
}

Categories