Json Webrequest To C# Object - c#

im currently developing an app which has an webrequest: I got the following class (got it from json2csharp converter):
class InventoryJsonData
{
public class RootObject
{
public bool Success { get; set; }
public object Error { get; set; }
public double Price { get; set; }
public string Username { get; set; }
}
}
Then i did the following coding:
ValueLoadingIndicator.IsActive = true;
var httpWebRequest = (HttpWebRequest)WebRequest.Create(JsonBaseuri + IDInput.Text);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
There is only one RootObject in the JSON Data. How do i get now the Price value so i can convert it into string and display it. I dont know what i need to add as c# code.
If you got helpful links to JSON c# tutorials and webrequest which are about this topic and can help me to move on they are appreciated as well.

Take a look and Newtonsoft Json.NET library: http://www.newtonsoft.com/json
You could also use WebClient class for you request - it's simpler to use.
Here is example code:
var url = JsonBaseuri + IDInput.Text;
var wc = new WebClient {Proxy = null};
var json = wc.DownloadString(url);
var responseModel = JsonConvert.DeserializeObject<InventoryJsonData>(json);
var price = responseModel.RootObject.Price;

HttpClient http = new System.Net.Http.HttpClient();
HttpResponseMessage response = await http.GetAsync(JsonBaseuri + IDInput.Text.ToString());
response.EnsureSuccessStatusCode();
string content = await response.Content.ReadAsStringAsync();
MessageDialog x = new MessageDialog(content, "JsonData");
This code gets me the Json File in windows universal apps ;) then i deserialize it -> read the answers above

Related

How to Seriailize an c# object into Json, while using httpClient?

I have a little program which should communicate with "Slack". In an older Version I used "Dictionary<string, string>" and then put them into UrlEncodedContent - which worked fine.
Now I am trying to create a Json-object, using Newtonsoft's Nuget-package and (in my opinion) formatting my object the way they say on their website.
Problem is, when I try to make a simple request, my program just runs to one specific line in the code(var response = await _httpClient.SendAsync(request);) and then it just ends. It doesn't throw an exception or display any kind of message, it simply ends on this line. I went through my code step by step while debugging, that's how I know it ends on exactly this line. And I just don't know why!
Now my code:
First, my object...
namespace BPS.Slack
{
public class JsonObject
{
//generally needed parameters
[JsonProperty("ok")]
public bool ok { get; set; }
[JsonProperty("error")]
public string error { get; set; }
[JsonProperty("channel")]
public string channel { get; set; }
[JsonProperty("token")]
private string token = "xoxp-MyToken";
[JsonProperty("as_user")]
public bool as_user = false;
[JsonProperty("username")]
public string username { get;set; }
//--------------------------------
//only needed for textmessages
[JsonProperty("text")]
public string text { get; set; }
//--------------------------------
//for posting messages with data attached
[JsonProperty("initial_comment")]
public string initial_comment { get; set; }
[JsonProperty("file")]
public string file { get; set; }
[JsonProperty("channels")]
public string channels { get; set; }
//--------------------------------
//for getting the latest message from a channel
[JsonProperty("count")]
public string count = "1";
[JsonProperty("unreads")]
public bool unreads = true;
}
}
now the client:
namespace BPS.Slack
{
public class BpsHttpClient
{
private readonly HttpClient _httpClient = new HttpClient { };
public Uri UriMethod { get; set; }
public BpsHttpClient(string webhookUrl)
{
UriMethod = new Uri(webhookUrl);
}
public async Task<HttpResponseMessage> UploadFileAsync(MultipartFormDataContent requestContent)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, UriMethod);
request.Content = requestContent;
var response = await _httpClient.SendAsync(request);
return response;
}
}
}
and the main
namespace TestArea
{
class MainArea
{
public static void Main( string[] args)
{
try
{
Task.WhenAll(SendMessage());
}
catch(Exception ass)
{
Console.WriteLine(ass);
Console.ReadKey();
}
}
private static async Task SendMessage()
{
var client = new BpsHttpClient("https://slack.com/api/im.history");
JsonObject JO = new JsonObject();
JO.channel = "DCW21NBHD";
var Json = JsonConvert.SerializeObject(JO);
var StringJson = new StringContent(Json, Encoding.UTF8);
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(StringJson);
var Response = await client.UploadFileAsync(content);
string AnswerContent = await Response.Content.ReadAsStringAsync();
Console.WriteLine(AnswerContent);
Console.ReadKey();
}
}
}
I had the same problem in my older version, BUT only as I wanted to DEserialize an answer I got from Slack. It had to do with my object I tried do deserialize the answer into. But this time I can not figure out what's wrong. But, as I said, I do not have any experience with using serialized objects as Json-property to send requests... anyone has an idea what is wrong with my code?
EDIT: This problem is kinda solved. But there is a follow up problem.
Okay, I found out that the reason for the abprubt termination was the
Task.WhenAll(SendMessage());
it should be
Task.WaitAll(SendMessage()); Why??? Somebody said I should use WhenAll, but obviously it doesn't work properly in this case...
Now I get a response from Slack, but now a different problem has arisen. When I use this method:
public async Task<HttpResponseMessage> UploadFileAsync(MultipartFormDataContent requestContent)
{
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, UriMethod);
request.Content = requestContent;
var response = await _httpClient.SendAsync(request);
return response;
}
I allways get the answer:
{"ok":false,"error":"invalid_form_data"}
so I tried to explicitly tell it the 'mediaType', I tried "application/json" and others, but with all of them I get the same error. Here is the full method that calls the upper mehtod:
private static async Task SendMessage()
{
var client = new BpsHttpClient("https://slack.com/api/chat.postMessage");
JsonObject JO = new JsonObject();
JO.channel = "DCW21NBHD";
JO.text = "This is so much fun :D !";
var Json = JsonConvert.SerializeObject(JO, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var StringJson = new StringContent(Json, Encoding.UTF8, "application/json");
var requestContent = new MultipartFormDataContent();
requestContent.Add(StringJson);
var Response = await client.UploadFileAsync(requestContent);
string AnswerContent = await Response.Content.ReadAsStringAsync();
}
When I use this method:
public async Task<HttpResponseMessage> SendMessageAsync(FormUrlEncodedContent content)
{
var response = await _httpClient.PostAsync(UriMethod, content);
return response;
}
so bascially I am passing "FormUrlEncodedContent" instead of "MultipartFormDataContent" in this, and then I get the response I want and can work wiht it. BUT this i of little use to me since I have to use "MultipartFormDataContent" to be able to send files with my requests.
Anyone have an idea what is failing here? Why does it not like the one content-type but the other one? I'd be gratefull for tipps and ideas!
You are serializing your object to Json and then adding it to a Multipart body, that's quite strange. Unless you're uploading binary data (eg Files), there is no need to use MultipartFormDataContent.
You are can directly post your JsonObject serialized as JSON:
public async Task<HttpResponseMessage> PostJsonAsync(StringContent content)
{
var response = await client.PostAsync(url, content);
return response;
}
var client = new BpsHttpClient("https://slack.com/api/im.history");
JsonObject JO = new JsonObject();
JO.channel = "DCW21NBHD";
var Json = JsonConvert.SerializeObject(JO);
var StringJson = new StringContent(Json, Encoding.UTF8);
var Response = await client.PostJsonAsync(content);
Also this is should be POST on the UploadFileAsync function.
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, UriMethod);
so I figured out that in the Main() the problem was this:
Task.WhenAll(SendMessage());
I should instead use:
Task.WaitAll(SendMessage());
Anyone who has more knowledge on this, please elaborate why!

Adobe Sign (echo sign) API sending document using C#

Okay I have limited understanding of working with API's
Im trying to get to grips with Adobe Sign API and hit a dead end, on there test page i have enterd this and it works
But i have no idea on how then do that in C#
I have tried the following, but know its missing the OAuth stuff and I'm just not sure what to try next.
by the way foo.GetAgreementCreationInfo() just gets the string that is in the screen shot, I just moved it out cus it was big and ugly
var foo = new Models();
var client = new RestClient("https://api.na1.echosign.com/api/rest/v5");
// client.Authenticator = new HttpBasicAuthenticator(username, password);
var request = new RestRequest("agreements/{AgreementCreationInfo}", Method.POST);
request.AddParameter("name", "value"); // adds to POST or URL querystring based on Method
request.AddUrlSegment("AgreementCreationInfo", foo.GetAgreementCreationInfo()); // replaces matching token in request.Resource
IRestResponse response = client.Execute(request);
var content = response.Content; // raw content as string
You are misinterpreting the API documentation. The Access-Token parameter needed in your API is clearly an HTTP header, while the AgreementCreationInfo is simply the request body in JSON format. There is no URI segment, so rewrite your code as follows:
var foo = new Models();
//populate foo
var client = new RestClient("https://api.na1.echosign.com/api/rest/v5");
var request = new RestRequest("agreements", Method.POST);
request.AddHeader("Access-Token", "access_token_here!");
// request.AddHeader("x-api-user", "userid:jondoe"); //if you want to add the second header
request.AddParameter("application/json", foo.GetAgreementCreationInfo(), ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var content = response.Content;
Please also be aware that in RESTSharp you do not need to manually serialize your body into JSON at all. If you create a strongly typed object (or just an anonymous object could be enough) that has the same structure of your final JSON, RESTSharp will serialize it for you.
For a better approach I strongly suggest you to replace this line:
request.AddParameter("application/json", foo.GetAgreementCreationInfo(), ParameterType.RequestBody);
With those:
request.RequestFormat = DataFormat.Json;
request.AddBody(foo);
Assuming your foo object is of type Models and has the following structure along with its properties:
public class Models
{
public DocumentCreationInfo documentCreationInfo { get; set; }
}
public class DocumentCreationInfo
{
public List<FileInfo> fileInfos { get; set; }
public string name { get; set; }
public List<RecipientSetInfo> recipientSetInfos { get; set; }
public string signatureType { get; set; }
public string signatureFlow { get; set; }
}
public class FileInfo
{
public string transientDocumentId { get; set; }
}
public class RecipientSetInfo
{
public List<RecipientSetMemberInfo> recipientSetMemberInfos { get; set; }
public string recipientSetRole { get; set; }
}
public class RecipientSetMemberInfo
{
public string email { get; set; }
public string fax { get; set; }
}
Link to AdobeSign Repository:
ADOBE SIGN SDK C# SHARP API Ver. 6
Adobe Sign API integrators - this is kind of hidden away in AdobeSigns GIT repositories. The link to all the generated SWAGGER classes (models/methods) for C# and REST client integrated C# project in a GIT project you can compile and use right inside your project as a project reference or compiled DLL. This project has been updated to use version 6 of the API. This was a huge time saver for me. I have provided a quick example below on how to use it. I hope this helps others save time as well.
Note you might have to switch out BasePath in the configuration.cs so you can retrieve the initial Adobe URI "BaseURI" call if you get 404 error.
Change BasePath = "http://localhost/api/rest/v6";
To:
BasePath = "https://api.echosign.com/api/rest/v6";
//include namespaces:
using IO.Swagger.Api;
using IO.Swagger.model.agreements;
using IO.Swagger.model.baseUris;
using IO.Swagger.model.transientDocuments;
using System.IO;
Then this quick minimal demonstrates BaseUri, Upload PDF a.k.a. Transient Document, then Create Agreement (Example 1 Basic Signer Minimal Options)
string transientDocumentId = "";
string adobesignDocKey = "";
string baseURI = "";
var apiInstanceBase = new BaseUrisApi();
var authorization = "Bearer " + apiKey; //Example as Integration Key, see adobesign docs For OAuth.
try
{
//___________________GET BASEURI ADOBE SIGN_________________________
BaseUriInfo resultBase = apiInstanceBase.GetBaseUris(authorization);
baseURI = resultBase.ApiAccessPoint; //return base uri
//___________________UPLOAD YOUR PDF THEN REF ADOBE SIGN_________________________
var apiInstanceFileUpload = new TransientDocumentsApi(baseURI + "api/rest/v6/");
TransientDocumentResponse resultTransientID = apiInstanceFileUpload.CreateTransientDocument(authorization, File.OpenRead([ENTER YOUR LOCAL FILE PATH]), null, null, _filename, null);
if (!String.IsNullOrEmpty(resultTransientID.TransientDocumentId))
{
transientDocumentId = resultTransientID.TransientDocumentId; //returns the transient doc id to use below as reference
}
var apiInstance = new AgreementsApi(baseURI + "api/rest/v6/");
//___________________CREATE ADOBE SIGN_________________________
var agreementId = ""; // string | The agreement identifier, as returned by the agreement creation API or retrieved from the API to fetch agreements.
var agreementInfo = new AgreementCreationInfo();
//transientDocument, libraryDocument or a URL (note the full namespace/conflicts with System.IO
List<IO.Swagger.model.agreements.FileInfo> useFile = new List<IO.Swagger.model.agreements.FileInfo>();
useFile.Add(new IO.Swagger.model.agreements.FileInfo { TransientDocumentId = transientDocumentId });
agreementInfo.FileInfos = useFile;
//Add Email To Send To:
List<ParticipantSetMemberInfo> partSigners = new List<ParticipantSetMemberInfo>();
partSigners.Add( new ParticipantSetMemberInfo { Email = "[ENTER VALID EMAIL SIGNER]", SecurityOption=null });
//Add Signer To Participant
List<ParticipantSetInfo> partSetInfo = new List<ParticipantSetInfo>();
partSetInfo.Add(new ParticipantSetInfo { Name = "signer1", MemberInfos = partSigners, Role = ParticipantSetInfo.RoleEnum.SIGNER, Order=1, Label="" });
agreementInfo.ParticipantSetsInfo = partSetInfo;
agreementInfo.SignatureType = AgreementCreationInfo.SignatureTypeEnum.ESIGN;
agreementInfo.Name = "Example Esign For API";
agreementInfo.Message = "Some sample Message To Use Signing";
agreementInfo.State = AgreementCreationInfo.StateEnum.INPROCESS;
AgreementCreationResponse result = apiInstance.CreateAgreement(authorization, agreementInfo, null, null);
adobesignDocKey = result.Id; //returns the document Id to reference later to get status/info on GET
}
catch (Exception ex)
{
//Capture and write errors to debug or display to user
System.Diagnostics.Debug.Write(ex.Message.ToString());
}

Creating a JSON object in ASP.Net

I am trying to create a JSON object in a .Net 5 application. The default options I am presented with are Microsoft.AspNet.Mvc.Formatters.Json, Microsoft.Extensions.Configuration.Json, and Newtonsoft.Json when I use the Visual Studio 2015 Qucik Actions on Json. My understanding is that Configuration.Json is for reading form the appsettings.json so it probably is not what I would use to create a JSON object. I can't find any real information on Formatters.Json, how to use it, or what it's intended use it. Newtonsoft.Json is will documented but is it better over the Formatters.Json? Which of the two should I be using?
Taken directly from ASP.NET Core 1 tests
var expected = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { foo = "abcd" }));
Also taken from the tests and slightly modified, call it with HttpClient to see how to send your json string to the server.
var response = await Client.PostAsync(
"http://localhost/api/ActionUsingSpecificFormatters",
new StringContent(yourJsonContent, Encoding.UTF8, "application/json"));
As per Newtonsoft you can simply encode, then do whatever you want after that.
Product product = new Product();
product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
string output = JsonConvert.SerializeObject(product);
//{
// "Name": "Apple",
// "ExpiryDate": "2008-12-28T00:00:00",
// "Price": 3.99,
// "Sizes": [
// "Small",
// "Medium",
// "Large"
// ]
//}
Product deserializedProduct = JsonConvert.DeserializeObject(output);
Putting it all together - I just tested this. Keep in mind this is a real generic pass through test from MVC 6 (ASP.NET 5 ie ASP.NET Core 1) :)
[HttpGet]
public async Task<string> Get()
{
var client = new HttpClient();
var customer = new Customer() { Name = "Schmo", Address = "1999 Purple Rain St" };
var customerJson = JsonConvert.SerializeObject(customer);
var response = await client.PostAsync(
"http://localhost:4815/api/Customer",
new StringContent(customerJson, Encoding.UTF8, "application/json"));
//just some template output to test which I'm getting back.
string resultJson = "{ 'Name':'adam'}";
if (response.StatusCode == HttpStatusCode.OK)
{
resultJson = await response.Content.ReadAsStringAsync();
var updatedCustomer = JsonConvert.DeserializeObject(resultJson);
}
return resultJson;
}
public class Customer
{
public string Name { get; set; }
public string Address { get; set; }
}
I would use Json.Net to create the JSON payloads for sure (Afterall, Microsoft does for Web Api).
Nuget Package Source:
Install-Package Newtonsoft.Json
Here is an example. If you want to call a REST api that returns a product when you make a GET call then you might do something like this.
public static class Main
{
string url = "https://TheDomainYouWantToContact.com/products/1";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "GET";
request.ContentType = "application/json";
request.Accept = "application/json";
var httpResponse = (HttpWebResponse)request.GetResponse();
var dataStream = httpResponse.GetResponseStream();
var reader = new StreamReader(dataStream);
var responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
// This is the code that turns the JSON string into the Product object.
Product productFromServer = JsonConvert.Deserialize<Product>(responseFromServer);
Console.Writeline(productFromServer.Id);
}
// This is the class that represents the JSON that you want to post to the service.
public class Product
{
public string Id { get; set; }
public decimal Cost { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
The exact same method can be used for POST and PUT as well.
You can use 3rd party assemblies to make this super easy too. We are the authors of DynamicApis.Api
Install-Package DynamicApis.Api
The code to make the same request using this client would be:
public static class Main
{
RestClient client = new RestClient();
string url = "https://YourDomain.com/products/1";
var productFromServer = client.Get<Product>(url);
Console.Writeline(productFromServer.Id);
}
you should use NewtonSoft.Json if you need to serialize objects as json
You shouldn't have to do anything special to send back Json data. The default output formatter is already Json, and if your Startup.cs file is somewhat normal, you should have a line similar to this:
services.AddMvc();
By default, this already contains the Json formatter, and your controller should autonegotiate the return type based on what the browser asked. So a controller like the following should work (taken from this Github issue, which contains some information on why/how this work):
public class ValuesController : ApiController
{
public SomeClass Get()
{
return new SomeClass();
}
public SomeClass Post([FromBody] SomeClass x)
{
return x;
}
}

web api receive object with null variables

I have webforms asp and web api. In web forms I try send to web api object of class this way:
HttpClient client = HttpClientHeader("", login, ClassMd5Calc.CalculateMd5Hash(password));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
UserTariff userTariff = new UserTariff();
userTariff.Login = "some value";
userTariff.Password = "some value";
userTariff.TariffName = "some value";
var json = new JavaScriptSerializer().Serialize(userTariff);
StringContent content = new StringContent(json);
content.Headers.ContentType = new MediaTypeHeaderValue("text/json");
HttpResponseMessage response = client.PostAsync("api/ChangeTariff/", content).Result;
This is my class (exist in data contract solution, so both project are use this class).
[Serializable]
public class UserTariff
{
public String Login { get; set; }
public String Password { get; set; }
public String TariffName { get; set; }
public decimal Balance { get; set; }
}
My web api receive package, but all field are null. What's wrong? How it's fix?
public class ChangeTariffController : ApiController
{
public void Post([FromBody] UserTariff mes)
{
//mes exist, but his property are null: mes.Login=null; mes.Password=null and e.t.c. but need value: "some value"
UPDATE 1.
I also tryed this code, but it show same error:
var content = new ObjectContent<UserTariff>(new UserTariff(), new JsonMediaTypeFormatter());
content.Headers.ContentType = new MediaTypeHeaderValue("text/json");
HttpResponseMessage response = client.PostAsync("api/ChangeTariff/", content).Result;
You can set the object content instead of the string content and should be using json media type formatter. This should fix the null bound variable in web api.
Also, use the newton soft json lib to convert the object to json.

reading my json response from a post request i sent

I made a post request class that I could re-use to make POST requests to an external api and return the objects they send me (JSON):
class PostRequest
{
private Action<DataUpdateState> Callback;
public PostRequest(string urlPath, string data, Action<DataUpdateState> callback)
{
Callback = callback;
// form the URI
UriBuilder fullUri = new UriBuilder(urlPath);
fullUri.Query = data;
// initialize a new WebRequest
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(fullUri.Uri);
request.Method = "POST";
// set up the state object for the async request
DataUpdateState dataState = new DataUpdateState();
dataState.AsyncRequest = request;
// start the asynchronous request
request.BeginGetResponse(new AsyncCallback(HandleResponse),
dataState);
}
private void HandleResponse(IAsyncResult asyncResult)
{
// get the state information
DataUpdateState dataState = (DataUpdateState)asyncResult.AsyncState;
HttpWebRequest dataRequest = (HttpWebRequest)dataState.AsyncRequest;
// end the async request
dataState.AsyncResponse = (HttpWebResponse)dataRequest.EndGetResponse(asyncResult);
if (dataState.AsyncResponse.StatusCode.ToString() == "OK")
{
Callback(dataState); // THIS IS THE LINE YOU SHOULD LOOK AT :)
}
}
}
public class DataUpdateState
{
public HttpWebRequest AsyncRequest { get; set; }
public HttpWebResponse AsyncResponse { get; set; }
}
}
the Callback method gets the datastate object and pushes it to this function:
public void LoadDashboard( DataUpdateState dataResponse )
{
Stream response = dataResponse.AsyncResponse.GetResponseStream();
//Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
//StreamReader readStream = new StreamReader(response, encode);
//readStream.Close();
Deployment.Current.Dispatcher.BeginInvoke(() => {
App.RootFrame.Navigate(new Uri("/Interface.xaml", UriKind.RelativeOrAbsolute));
});
}
I'm now unsure of how to get the body of that reply that has been sent to me from the API. It is returning a json format, I need to be able to map it to a nice C# class and use it to display stuff on the phone.
I can't find an example that doesn't use JSON.NET (which doesn't have an assembly for windows phone 8)
This is error I get installing HTTPClient class:
Attempting to resolve dependency 'Microsoft.Bcl (≥ 1.1.3)'.
Attempting to resolve dependency 'Microsoft.Bcl.Build (≥ 1.0.4)'.
Successfully installed 'Microsoft.Bcl.Build 1.0.10'.
Successfully installed 'Microsoft.Bcl 1.1.3'.
Successfully installed 'Microsoft.Net.Http 2.2.13'.
Successfully added 'Microsoft.Bcl.Build 1.0.10' to UnofficialPodio.
Executing script file ***\packages\Microsoft.Bcl.Build.1.0.10\tools\Install.ps1'.
This reference cannot be removed from the project because it is always referenced by the compiler.
This reference cannot be removed from the project because it is always referenced by the compiler.
This reference cannot be removed from the project because it is always referenced by the compiler.
This reference cannot be removed from the project because it is always referenced by the compiler.
Executing script file ***\packages\Microsoft.Bcl.Build.1.0.10\tools\Uninstall.ps1'.
Successfully uninstalled 'Microsoft.Bcl 1.1.3'.
Successfully uninstalled 'Microsoft.Bcl.Build 1.0.10'.
Install failed. Rolling back...
Failed to add reference to 'System.IO'.
"{
\"access_token\": \"123803120312912j\",
\"token_type\": \"bearer\",
\"ref\": {
\"type\": \"user\",
\"id\": 123123
},
\"expires_in\": 28800,
\"refresh_token\": \"234234f23f423q432f\"
}"
...
public class Auth
{
[DataMember(Name = "access_token")]
public string AccessToken { get; set; }
[DataMember(Name = "token_type")]
public string TokenType { get; set; }
[DataMember(Name = "expires_in")]
public string ExpiresIn { get; set; }
[DataMember(Name = "refresh_token")]
public string RefreshToken { get; set; }
//[DataMember(Name = "ref")]
//public string Ref { get; set; }
}
To get the response data you need to call GetResponseStream() on the HttpWebResponse object and then read from the stream. Something like this:
using (Stream s = response.GetResponseStream())
{
using (TextReader textReader = new StreamReader(s, true))
{
jsonString = textReader.ReadToEnd();
}
}
To get the data from the json string, you need to create a data contract class to describe the json data exactly like this:
[DataContract]
public class ApiData
{
[DataMember(Name = "name")] <--this name must be the exact name of the json key
public string Name { get; set; }
[DataMember(Name = "description")]
public string Description { get; set; }
}
Next you can deserialize the json object from the string:
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ApiData));
ApiData obj = (ApiData)serializer.ReadObject(stream);
return obj;
}
WebRequest will work fine, but I would recommend installing the NuGet package for the HttpClient class. It makes life much simpler. for instance, you could make the above request code in just a few lines:
HttpClient httpClient = new HttpClient();
HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), escapedUrl);
HttpResponseMessage response = await httpClient.SendAsync(msg);
In answer to you question below, here is the generic json converter code that I use:
public static class JsonHelper
{
public static T Deserialize<T>(string json)
{
using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
T obj = (T)serializer.ReadObject(stream);
return obj;
}
}
public static string Serialize(object objectToSerialize)
{
using (MemoryStream ms = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(objectToSerialize.GetType());
serializer.WriteObject(ms, objectToSerialize);
ms.Position = 0;
using (StreamReader sr = new StreamReader(ms))
{
return sr.ReadToEnd();
}
}
}
}
JSON.Net does support windows phone 8, it's available as a portable class library according to this answer.
Just try adding the package via nuget...

Categories