How to parse Json WebApi response containing C# list - c#

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;

Related

Parsing Json response from Httpwebrequest

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

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.

sending push notification using FCM on android device

I can able to send the push notification on my android application using the console. but using server side code, I get the successfully message send notification but actually notification does not able to receive at device end. Please, tell me what is wrong with my code:
public static string SendPushNotification() {
try {
string applicationID = "AAAA4GkXVHA:....-qRw";
string senderId = "963..28";
string deviceId = "APA91bHLV...IC4s";
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.ContentType = "application/json";
var data = new {
to = deviceId,
notification = new {
body = "hema",
title = "hem",
//priority = "normal",
//sound = "Enabled"
},
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(data);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream()) {
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse()) {
using (Stream dataStreamResponse = tResponse.GetResponseStream()) {
using (StreamReader tReader = new StreamReader(dataStreamResponse)) {
String sResponseFromServer = tReader.ReadToEnd();
string str = sResponseFromServer;
return str;
}
}
}
}
}
catch (Exception ex) {
string str = ex.Message;
return str;
}
}
where I got the response in return is as follows :
{"multicast_id":8288766196764532656,"success":1,"failure":0,"canonical_ids":0,"results":[{"message_id":"0:1481612825945796%6ad79a87f9fd7ecd"}]}
Sending the json in right format:
{
"to" : "APA91bHLV__P6Qer8U70j82blZt0VdDgc2zo_4DtAD4_MtE-......",
"notification" : {
"body" : "Success!",
"title" : "Hema",
"icon" : "myicon"
}
}
To check it properly, you can also use the postman:
Even I experienced the same problem. Finish all the steps in connecting the FCM from Client side. If you implement GetMessage() method from client side, only then your device is able to get the Notification from Server side
I wrote a small tutorial for this: https://www.kendar.org/?p=/tutorials/notifications with an Android app and a .Net core Server. To summarize here is the "main" server code
public NotificationResult Send(NotificationModel messageData)
{
var result = "-1";
var webAddr = "https://fcm.googleapis.com/fcm/send";
var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add(HttpRequestHeader.Authorization, "key=PROJECTSETTINGS->Cloud Messagings->Server Key");
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string strNJson = JsonConvert.SerializeObject(new NotificationMessage
{
To = "/topics/ServiceNow",
Data = new NotificationData
{
Description = messageData.Description,
IncidentNo = messageData.IncidentNo,
ShortDesc = messageData.ShortDesc
},
Notification = new Notification
{
Title = "ServiceNow: Incident No." + messageData.IncidentNo,
Text = "Notification"
}
});
streamWriter.Write(strNJson);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
result = streamReader.ReadToEnd();
}
return new NotificationResult
{
Result = result
};
}
And the classes that wrap the message to FCM (with the Json annotations to correct the mismatch between .Net and Json naming standards)
public class NotificationData
{
public string ShortDesc { get; set; }
public long IncidentNo { get; set; }
public string Description { get; set; }
}
public class Notification
{
public Notification()
{
Sound = "default";
}
[JsonProperty("title")]
public string Title { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("sound")]
public string Sound { get; set; }
}
public class NotificationMessage
{
[JsonProperty("to")]
public string To { get; set; }
[JsonProperty("data")]
public NotificationData Data { get; set; }
[JsonProperty("notification")]
public Notification Notification { get; set; }
}

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

How to get the canonical ids from the response in the following context?

I am totally new to GCM and I have used the below method to send messages to the GCM server.
public string SendMessage(string RegistrationID, string Message, string AuthString)
{
//-- Create C2DM Web Request Object --//
HttpWebRequest Request = (HttpWebRequest)WebRequest.Create("https://android.clients.google.com/c2dm/send");
Request.Method = "POST";
Request.KeepAlive = false;
//-- Create Query String --//
NameValueCollection postFieldNameValue = new NameValueCollection();
postFieldNameValue.Add("registration_id", RegistrationID);
postFieldNameValue.Add("collapse_key", "1");
postFieldNameValue.Add("delay_while_idle", "0");
// postFieldNameValue.Add("data.message", Message);
postFieldNameValue.Add("data.payload", Message);
string postData = GetPostStringFrom(postFieldNameValue);
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
Request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
Request.ContentLength = byteArray.Length;
Request.Headers.Add(HttpRequestHeader.Authorization, "GoogleLogin auth=" + AuthString);
//-- Delegate Modeling to Validate Server Certificate --//
ServicePointManager.ServerCertificateValidationCallback += delegate(
object
sender,
System.Security.Cryptography.X509Certificates.X509Certificate
pCertificate,
System.Security.Cryptography.X509Certificates.X509Chain pChain,
System.Net.Security.SslPolicyErrors pSSLPolicyErrors)
{
return true;
};
//-- Create Stream to Write Byte Array --//
Stream dataStream = Request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//-- Post a Message --//
WebResponse Response = Request.GetResponse();
HttpStatusCode ResponseCode = ((HttpWebResponse)Response).StatusCode;
if (ResponseCode.Equals(HttpStatusCode.Unauthorized) || ResponseCode.Equals(HttpStatusCode.Forbidden))
{
return "Unauthorized - need new token";
}
else if (!ResponseCode.Equals(HttpStatusCode.OK))
{
return "Response from web service isn't OK";
//Console.WriteLine("Response from web service not OK :");
//Console.WriteLine(((HttpWebResponse)Response).StatusDescription);
}
StreamReader Reader = new StreamReader(Response.GetResponseStream());
string responseLine = Reader.ReadLine();
Reader.Close();
return responseLine;
}
I need to handle the canonical ids in this situation. I saw the below code snippet which can be used in Java.
if (result.getMessageId() != null) {
String canonicalRegId = result.getCanonicalRegistrationId();
if (canonicalRegId != null) {
// same device has more than on registration ID: update database
}
} else {
String error = result.getErrorCodeName();
if (error.equals(Constants.ERROR_NOT_REGISTERED)) {
// application has been removed from device - unregister database
}
}
But how can I achieve the same in C#? It doesn't have the getCanonicalIds method since its a standard web response I am getting. How can I find the canonical ids and remove them from the table? Please advice.
canonical Ids are Ids of devices that have already been registered under a different Id. When you don't have such Id, the canonical_ids element will give you 0. But if it has a value then you canonical_ids element in the response will show the count. In your response these ids will be indicated as "registration_id". And these will be in the order the requests were sent. So if the 3rd and 4th elements of your response string have a value for "registration_ids" it means that the 3rd and 4th element ids you have sent in the request are not the right one. Replace them from the table with Ids provided in "registration_ids" in the response. Below is the code to get those indexes and ids from C# code.
class Program
{
static void Main(string[] args)
{
List<String> ids = new List<String>();
String json ="{\"multicast_id\": \"xxxxx\",\"success\": 7,\"failure\": 0,\"canonical_ids\": 2,\"results\": [{\"message_id\": \"0:xxx%xxxxx\"}, {\"message_id\": \"0:xxx%xxxxx\"}, {\"registration_id\": \"456\",\"message_id\": \"0:xxx%xxxxx\"}, {\"message_id\": \"0:xxx%xxxxx\"}, {\"message_id\": \"0:xxx%xxxxx\"}, {\"registration_id\": \"123\",\"message_id\": \"0:xxx%xxxxx\"}, {\"message_id\": \"0:xxx%xxxxx\"}]}";
RootObject decryptedMessage = new JavaScriptSerializer().Deserialize<RootObject>(json);
int position = 0;
Dictionary<int, String> canonicalIdsAndIndexes = new Dictionary<int, string>();
foreach (var item in decryptedMessage.results)
{
if (item.registration_id != null)
{
canonicalIdsAndIndexes.Add(position, item.registration_id);
Console.WriteLine("message id: {0}, registrationid: {1}", item.message_id, item.registration_id);
}
position++;
}
Console.ReadLine();
}
}
public class Result
{
public string message_id { get; set; }
public string registration_id { get; set; }
}
public class RootObject
{
public string multicast_id { get; set; }
public int success { get; set; }
public int failure { get; set; }
public int canonical_ids { get; set; }
public List<Result> results { get; set; }
}

Categories