Cannot Deserilize Json Format - c#

I cannot deserilize this Json result
I have this code for that
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
using (TextReader reader = new StreamReader(responseStream, true))
{
valor = reader.ReadToEnd();
}
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(valor)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(List<ApiData>));
List<ApiData> obj = (List<ApiData>)serializer.ReadObject(stream);
}
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
}
throw;
}
But the result obj is null
ApiData Example
[DataContract]
public class ApiData
{
[DataMember(Order = 1)]
public string coArt { get; set; }
[DataMember(Order = 2)]
public string artDes { get; set; }
[DataMember(Order = 3)]
public string fechaReg { get; set; }
[DataMember(Order = 4)]
public bool manjSer { get; set; }
[DataMember(Order = 5)]
}
Anyone can help me or tell me whats wrong with the code or format casting? thanks you

Your root JSON entity isn't a list, it's an object with name/value pairs, the first name being 0 and the values being instances of your ApiData class. To deserialize this, you should use a Dictionary<string, ApiData> (or Dictionary<int, ApiData> if you are sure that only numbers appear as keys).
Thus:
var serializer = new DataContractJsonSerializer(typeof(Dictionary<string, ApiData>), new DataContractJsonSerializerSettings { UseSimpleDictionaryFormat = true });
var dict = (Dictionary<string, ApiData>)serializer.ReadObject(stream);
Note that you must set DataContractJsonSerializerSettings.UseSimpleDictionaryFormat = true to use DataContractJsonSerializer to parse dictionaries in this format -- and this setting is only available starting in .Net 4.5.

Related

Invalidcastexception JsonConvert.DeserializeObject

I am getting an invalid cast exception that the specified cast is not valid. On this line:
RootObject mountain = JsonConvert.DeserializeObject<RootObject>(json1);
From the documentation this should be fine? I can see the console output is fine?
Response: [{"Height_ft": 2999.0, "Height_m": 914.0, "ID": "c1",
"Latitude": 57.588007, "Longitude": -5.5233564, "Name": "Beinn Dearg",
"humidity": 0.81, "snowCover": 4.99, "temperature": 63.0}]
Spinner spinner = (Spinner)sender;
string urlmountain = "http://removed.azurewebsites.net/api/Mountains?name=";
JsonValue json1 = FetchMountain(urlmountain+string.Format("{0}", spinner.GetItemAtPosition(e.Position)));
//below.................................
RootObject mountain = JsonConvert.DeserializeObject<RootObject>(json1); //this line
string toast = mountain.Name;
Toast.MakeText(this, toast, ToastLength.Long).Show();
private JsonValue FetchMountain(string urlmountain)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(urlmountain));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = request.GetResponse())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc1 = JsonObject.Load(stream);
Console.Out.WriteLine("Response: {0}", jsonDoc1.ToString());
// Return the JSON document:
return jsonDoc1;
}
}
}
public class RootObject
{
public string ID { get; set; }
public double? Latitude { get; set; }
public double? Longitude { get; set; }
public string Name { get; set; }
public double? Height_m { get; set; }
public double? Height_ft { get; set; }
public double? temperature { get; set; }
public double? humidity { get; set; }
public double? snowCover { get; set; }
public override string ToString()
{
return Name;
}
}
The json data being returned is an array of objects, not a single object, as denoted by the opening and closing brackets []. You need to deserialize to an array or a list:
var mountains = JsonConvert.DeserializeObject<List<RootObject>>(json);
To access the first mountain from the deserialized payload, use .FirstOrDefault().
var mountain = mountains.FirstOrDefault();
if (mountain != null)
{
string toast = mountain.Name;
Toast.MakeText(this, toast, ToastLength.Long).Show();
}
It looks like your JSON is an Array of objects. You should be able to deserialize the array and get the first one like so:
RootObject mountain = JsonConvert.DeserializeObject<RootObject[]>(json1)[0];
One thing to note is that you are sort of mixing technologies here. JsonValue is from the System.Json namespace, whereas JsonConvert is from the Newtonsoft.Json (i.e. JSON.Net) namespace. If you wanted to go strictly with JSON.Net, you could do something like this:
private RootObject FetchMountain(string urlmountain)
{
// Create an HTTP web request using the URL:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(urlmountain));
request.ContentType = "application/json";
request.Method = "GET";
using (WebResponse response = request.GetResponse())
using (Stream stream = response.GetResponseStream())
using (StreamReader streamReader = new StreamReader(stream))
{
JsonSerializer serializer = new JsonSerializer();
RootObject[] mountains = (RootObject[])serializer.Deserialize(streamReader, typeof(RootObject[]));
return (mountains.Length > 0) ? mountains[0] : null;
}
}

Parsing uniquely named nested JSON

Preface: I know of JSON.NET but I cannot use it (client machine).
I need to parse the JSON returned by http://api.fixer.io/latest?base=USD into 3 columns, date, currencyCode, and rate. The issue is with the nested "rates" portion. The currency code is the name of the first element which means I can't use "key" and "value" properties. The only way I know of is to hardcode each possible currency code, which is what I have currently in the code below. I want to be able to use key/value pairs to pull the code/rate simultaneously.
The JSON:
{"base":"USD",
"date":"2016-07-12",
"rates": {
"AUD":1.3101,
"BGN":1.7633,
"BRL":3.2829,
"CAD":1.3029,
etc....}
}
My code so far:
static void Main(string[] args)
{
var curDate = "2001-01-01";
var URL = #"http://api.fixer.io/" + curDate + "?base=USD";
Console.WriteLine(URL);
//WebRequest wrGetURL = WebRequest.Create(URL);
var text = "";
//wrGetURL.ContentType = "application/json; charset=utf-8";
HttpWebRequest httpWebRequest = System.Net.WebRequest.Create(URL) as HttpWebRequest;
using (HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse)
{
if (httpWebResponse.StatusCode != HttpStatusCode.OK)
{
throw new Exception(string.Format("Server error (HTTP {0}: {1}).",
httpWebResponse.StatusCode, httpWebResponse.StatusDescription));
}
Stream stream = httpWebResponse.GetResponseStream();
DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(typeof(JSONRead));
JSONRead objResponse = (JSONRead)dataContractJsonSerializer.ReadObject(stream);
Console.WriteLine(objResponse.rates.AUD);
}
Console.ReadLine();
}
[DataContract]
public class JSONRead
{
[DataMember(Name = "date")]
public string date { get; set; }
[DataMember(Name = "rates")]
public Rates rates { get; set; }
[DataMember(Name = "base")]
public string bases { get; set; }
}
[DataContract]
public class Rates
{
[DataMember(Name = "AUD")]
public string AUD { get; set; }
//[DataMember(Name = "key")]
//public string key { get; set; }
//[DataMember(Name = "value")]
//public string value { get; set; }
}
What I am trying to return:
Date Code Rate
2016-07-12 AUD 1.3101
2016-07-12 GBN 1.7633
etc...
I had to use the DataContractJsonSerializerSettings and set UseSimpleDictionaryFormat to true. It then reads the nested object into a Dictionary object properly. Thanks for the help #Plutonix.

How to get UserContactLists from constant contact using c#

I am going to use Constant contact for email marketing. I am not getting how to get userContactList which are all there in my constant contact account.If anyone have any idea please help me.
Thanks in advance
Here is some code I wrote a while ago that returns the user list ID based on the name of an existing user list. its all C# and uses RESTSharp library which you can install inside your VS project using Nuget.
public static string GetContactListIDByListName(string listname)
{
feedData = string.Empty;
id = string.Empty;
name = string.Empty;
status = string.Empty;
modified_date = string.Empty;
created_date = string.Empty;
contact_count = 0;
Stream stream = null;
StreamReader streamReader = null;
var client = new RestClient(ccURL);
var request = new RestRequest("/v2/lists?modified_since=[DATE]&api_key=[API-KEY]", Method.GET);
request.AddHeader("Authorization", "Bearer [ACCESS-TOKEN]");
request.AddHeader("X-Originating-Ip", "[SERVER-IP]");
request.AddHeader("Accept", "application/json");
IRestResponse response = client.Execute(request);
feedData = response.Content;
// DESERIALIZE Mashery JSON Response
byte[] byteArray = Encoding.ASCII.GetBytes(feedData);
MemoryStream myStream = new MemoryStream(byteArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(Mashery.GetAllListsDef[]));
object result = serializer.ReadObject(myStream);
Mashery.GetAllListsDef[] jsonObj = result as Mashery.GetAllListsDef[];
foreach (Mashery.GetAllListsDef myResult in jsonObj)
{
if (myResult.name.ToUpper().Equals(listname.ToUpper()))
{
return myResult.id.ToString();
}
}
return "";
}
// JSON Definition For [GET All Lists] End Point Method
[Serializable, XmlRoot("GetAllListsDef"), DataContract(Name = "GetAllListsDef")]
public class GetAllListsDef
{
[XmlElement("id"), DataMember(Name = "id")]
public string id { get; set; }
[XmlElement("name"), DataMember(Name = "name")]
public string name { get; set; }
[XmlElement("status"), DataMember(Name = "status")]
public string status { get; set; }
[XmlElement("created_date"), DataMember(Name = "created_date")]
public string created_date { get; set; }
[XmlElement("modified_date"), DataMember(Name = "modified_date")]
public string modified_date { get; set; }
[XmlElement("contact_count"), DataMember(Name = "contact_count")]
public string contact_count { get; set; }
}

Serializing .NET object to JSON

I tried the following code to serialize a .NET object to JSON, but i keep getting blank text. What am I doing wrong?
[DataContract]
public class JsonObject2
{
[DataMember(Name = "field1")]
string field1 { get; set; }
[DataMember(Name = "field2")]
string field2 { get; set; }
[DataMember(Name = "field3")]
string[] test = { "heshan", "perera" };
}
The object, I attempt to serialize and display the resulting JSON string in a message box, but all i get is blank.
MemoryStream s = new MemoryStream();
DataContractJsonSerializer dcjs2 = new DataContractJsonSerializer((typeof(JsonObject2)));
JsonObject2 obj2 = new JsonObject2();
dcjs2.WriteObject(s, obj2);
StreamReader r = new StreamReader(s);
String x = r.ReadToEnd();
MessageBox.Show(x);
Try adding:
s.Position = 0;
just before you create the StreamReader.

iphone push notification urbanairship

i"m want to send notification from my server side (c#) via urbanairship api
is there any example in c# how to do it?
thanks
Basically...
using System;
using System.IO;
using System.Net;
using System.Text;
namespace Examples.System.Net
{
public class WebRequestPostExample
{
public static void Main ()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create ("https://go.urbanairship.com/api/push/");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
broken out to multiple lines so you can read it
string postData = "{
"device_tokens": [
"some device token",
"another device token"
],
"aliases": [
"user1",
"user2"
],
"tags": [
"tag1",
"tag2"
],
"schedule_for": [
"2010-07-27 22:48:00",
"2010-07-28 22:48:00"
],
"exclude_tokens": [
"device token you want to skip",
"another device token you want to skip"
],
"aps": {
"badge": 10,
"alert": "Hello from Urban Airship!",
"sound": "cat.caf"
}
}";
and then
byte[] byteArray = Encoding.UTF8.GetBytes (postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
//Do a http basic authentication somehow
string username = "<application key from urban airship>";
string password = "<master secret from urban airship>";
string usernamePassword = username + ":" + password;
CredentialCache mycache = new CredentialCache();
mycache.Add( new Uri( "https://go.urbanairship.com/api/push/" ), "Basic", new NetworkCredential( username, password ) );
request.Credentials = mycache;
request.Headers.Add( "Authorization", "Basic " + Convert.ToBase64String( new ASCIIEncoding().GetBytes( usernamePassword ) ) );
// Get the request stream.
Stream dataStream = request.GetRequestStream ();
// Write the data to the request stream.
dataStream.Write (byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close ();
// Get the response.
WebResponse response = request.GetResponse ();
// Display the status.
Console.WriteLine (((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream ();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader (dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd ();
// Display the content.
Console.WriteLine (responseFromServer);
// Clean up the streams.
reader.Close ();
dataStream.Close ();
response.Close ();
}
}
}
See api docs, msdn and here for more on https
The accepted answer doesn't work, you need to change the following line:
request.ContentType = "application/x-www-form-urlencoded";
to
request.ContentType = "application/json";
Complete working code shown below:
using System;
using System.IO;
using System.Net;
using System.Text;
namespace UrbanAirship_Tes_1
{
class Program
{
public static void Main()
{
// Create a request using a URL that can receive a post.
WebRequest request = WebRequest.Create("https://go.urbanairship.com/api/push/");
request.Credentials = new NetworkCredential("pvYMExk3QIO7p2YUs6BBkg", "rO3DsucETRadbbfxHkd6qw");
// Set the Method property of the request to POST.
request.Method = "POST";
// Create POST data and convert it to a byte array.
//WRITE JSON DATA TO VARIABLE D
string postData = "{\"aps\": {\"badge\": 1, \"alert\": \"Hello from Urban Airship!\"}, \"device_tokens\": [\"6334c016fc643baa340eca25bc661d15055a07b475e9a6108f3f644b15dd05ac\"]}";
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
// Console.WriteLine(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
Console.WriteLine(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
}
}
public class PushNotificationHelper
{
private readonly ILog log4netEngine;
private string UrbanAirshipApplicationKey { get; set; }
private string UrbanAirshipApplicationSecret { get; set; }
private string UrbanAirshipApplicationMasterSecret { get; set; }
public PushNotificationHelper(string UrbanAirshipApplicationKey, string UrbanAirshipApplicationSecret, string UrbanAirshipApplicationMasterSecret)
{
log4netEngine = LogManager.GetLogger(typeof(PushNotificationHelper).Name);
this.UrbanAirshipApplicationKey = UrbanAirshipApplicationKey;
this.UrbanAirshipApplicationSecret = UrbanAirshipApplicationSecret;
this.UrbanAirshipApplicationMasterSecret = UrbanAirshipApplicationMasterSecret;
}
public void PushNotification2iPhones(string alertText, string[] apids, string extra)
{
if (!string.IsNullOrEmpty(alertText) && apids.Length > 0)
{
iPhonePushNotification pushNotification = new iPhonePushNotification
{
MessageBody = new iPhonePushNotificationMessageBody
{
Alert = alertText
},
Extra = extra,
APIDs = apids
};
string jsonMessageRequest = pushNotification.ToJsonString();
try
{
SendMessageToUrbanAirship(jsonMessageRequest);
log4netEngine.InfoFormat("Push Notification Success , iPhoneDevice:{0}, message:{1},extra:{2}", string.Join(",", apids), alertText, extra);
}
catch (Exception ex)
{
log4netEngine.InfoFormat("Push Notification Error:{0}, iPhoneDevice:{1}, message:{2},extra:{3}", ex.Message, string.Join(",", apids), alertText, extra);
}
}
}
public void PushNotification2Androids(string alertText, string[] apids, string extra)
{
if (!string.IsNullOrEmpty(alertText) && apids.Length > 0)
{
AndroidPushNotification pushNotification = new AndroidPushNotification
{
MessageBody = new AndroidPushNotificationMessageBody
{
Alert = alertText,
Extra = extra
},
APIDs = apids
};
string jsonMessageRequest = pushNotification.ToJsonString();
try
{
SendMessageToUrbanAirship(jsonMessageRequest);
log4netEngine.InfoFormat("Push Notification Success , androidDevice:{0}, message:{1},extra:{2}", string.Join(",", apids), alertText, extra);
}
catch (Exception ex)
{
log4netEngine.InfoFormat("Push Notification Error:{0}, androidDevice:{1}, message:{2},extra:{3}", ex.Message, string.Join(",", apids), alertText, extra);
}
}
}
private void SendMessageToUrbanAirship(string jsonMessageRequest)
{
var uri = new Uri("https://go.urbanairship.com/api/push/");
var encoding = new UTF8Encoding();
var request = WebRequest.Create(uri);
request.Method = "POST";
request.Credentials = new NetworkCredential(this.UrbanAirshipApplicationKey, this.UrbanAirshipApplicationMasterSecret);
request.ContentType = "application/json";
request.ContentLength = encoding.GetByteCount(jsonMessageRequest);
using (var stream = request.GetRequestStream())
{
stream.Write(encoding.GetBytes(jsonMessageRequest), 0, encoding.GetByteCount(jsonMessageRequest));
stream.Close();
var response = request.GetResponse();
response.Close();
}
}
}
public class NotificationToPush
{
public int ReceiverUserID { get; set; }
public string Message { get; set; }
public Dictionary<string, string> Extra { get; set; }
}
[DataContract(Name = "PushNotificationBody")]
internal class PushNotification
{
public string ToJsonString()
{
var result = JsonConvert.SerializeObject(this);
return result;
}
}
[DataContract(Name = "iPhonePushNotification")]
internal class iPhonePushNotification : PushNotification
{
[DataMember(Name = "aps")]
public iPhonePushNotificationMessageBody MessageBody { get; set; }
[DataMember(Name = "extra")]
public string Extra { get; set; }
[DataMember(Name = "device_tokens")]
public string[] APIDs { get; set; }
}
[DataContract(Name = "iPhonePushNotificationMessageBody")]
internal class iPhonePushNotificationMessageBody
{
[DataMember(Name = "alert")]
public string Alert { get; set; }
}
[DataContract(Name = "AndroidPushNotification")]
internal class AndroidPushNotification : PushNotification
{
[DataMember(Name = "android")]
public AndroidPushNotificationMessageBody MessageBody { get; set; }
[DataMember(Name = "apids")]
public string[] APIDs { get; set; }
}
[DataContract(Name = "AndroidPushNotificationMessageBody")]
internal class AndroidPushNotificationMessageBody
{
[DataMember(Name = "alert")]
public string Alert { get; set; }
[DataMember(Name = "extra")]
public string Extra { get; set; }
}
Here is how to do it using the System.Net.Http.HttpClient async methods.
var handler = new HttpClientHandler { Credentials = new NetworkCredential(urbanairshipapiKey, urbanairshipApiAppMasterSecret) };
var client = new HttpClient(handler);
var added = client.DefaultRequestHeaders.TryAddWithoutValidation("Accept", "application/vnd.urbanairship+json; version=3;");
var response = await client.PostAsync(apiUrl + "/push/", new StringContent(json, Encoding.UTF8, "application/json"));
I wrote a c# library to simplify the use of the UrbanAirship API
https://github.com/JeffGos/urbanairsharp
Hope it helps!

Categories

Resources