Convert JsonObject to List<T> - c#

I have this json value that I want to convert to a List
[{
"id_cuenta": 1,
"nombre": "Mercedes Luj\u00e1n",
"apellido": "Llano",
"ci": 123,
"telefono": 123456789,
"dispositivo_id": "355790037549877",
"password": "holaa",
"created_at": "2016-07-02 11:36:57",
"updated_at": "2016-07-09 09:56:53"
}]
This is my code so far:
private List<cuentaObtener> mCuenta;
btnLogIn.Click += async(object sender, EventArgs e) =>
{
string url = "http://localhost:8000/api/v1/cuenta_ci/" + ci.Text + "";
JsonValue json = await ObtenerCi(url);
private async Task<JsonValue> ObtenerCi(string url)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(url));
request.ContentType = "application/json";
request.Method = "GET";
// Send the request to the server and wait for the response:
using (WebResponse response = await request.GetResponseAsync())
{
// Get a stream representation of the HTTP web response:
using (Stream stream = response.GetResponseStream())
{
// Use this stream to build a JSON document object:
JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));
//Code to convert JsonObject to List<T>
// Return the JSON document:
return jsonDoc;
}
}
This is my class where I want to store values:
public class cuentaObtener
{
public int id_cuenta { get; set; }
public string nombre { get; set; }
public string apellido { get; set; }
public int ci { get; set; }
public int telefono { get; set; }
public string dispositivo_id { get; set; }
public string password { get; set; }
}
How can I achieve this? Thank you in advance!

You need to download this Nuget Package (Right Click Project > Manager Nuget Packages)
Then you can use :
string json = null;
using (StreamReader stream = new StreamReader(response.GetResponseStream()))
{
json = stream.ReadToEnd();
}
List<cuentaObtener> JsonConvert.DeserializeObject<List<cuentaObtener>>(json);
If you're using HttpClient:
var response = await httpClient.GetAsync(url);
string json = await response.Content.ReadAsStringAsync();
List<cuentaObtener> JsonConvert.DeserializeObject<List<cuentaObtener>>(json);

Related

JSON returned from the Web API is not in proper format

I am trying to return a JSON for the Web API I am building. The API returns the JSON with \ slashes that makes difficult for my other application to consume this API.
" {\"#odata.context\":\"https://science.com/odata/$metadata#EMPLOYEE\",\"value\":[{\"Id\":5000004,\"Name\":\"Account\"}]}"
But I am expecting a response like
{
"#odata.context": "https://science.com/odata/$metadata#EMPLOYEE",
"value": [
{
"Id": 5000004,
"Name": "Account"
}]}
Below is the code for my Web API
public async Task<string> GetEmployee(string instance)
{
.....
EmployeeDTO.RootObject returnObj = new EmployeeDTO.RootObject();
var responsedata = "";
try
{
using (var client_Core = new HttpClient())
{
....
string core_URL = BaseURL_Core+URL_instance;
var response = client_Core.GetAsync(core_URL).Result;
responsedata = await response.Content.ReadAsStringAsync();
}
}
catch (Exception ex)
{
throw ex;
}
return responsedata;
}
I have also added the Content type in the WebAPIConfig file like below
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
But I am still getting the JSON with the slashes
responsedata = await response.Content.ReadAsStringAsync();
Above code returns string and you return the same response back. As the result, it is not well-formed JSON you expected.
If you want to return proper JSON, you'll need to convert string to JSON before returning it.
public async Task<Data> GetEmployee(string instance)
{
string responsedata = " {\"#odata.context\":\"https://science.com/odata/$metadata#EMPLOYEE\",\"value\":[{\"Id\":5000004,\"Name\":\"Account\"}]}";
return JsonConvert.DeserializeObject<Data>(responsedata);
}
public class Data
{
[JsonProperty("#odata.context")]
public string ODataContext { get; set; }
public Value[] Value { get; set; }
}
public class Value
{
public int Id { get; set; }
public string Name { get; set; }
}

How to return WebRequest Multidimensional JSON?

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

invalid casting exception from datacontract json serializer

I am working on a project for Windows Phone 7.1 in Visual Studio 2010. I am trying to download JSON data and deserialize it into a list of objects. The following is the code I am using to build the web request and handle the response.
public class HttpGetTask<T>
{
public HttpGetTask(string url, Action<T> onPostExecute)
{
this.Url = url;
this.OnPostExecute = onPostExecute;
}
public void Execute()
{
MessageBox.Show("We are in the task Execute method");
if (this.OnPreExecute != null)
{
this.OnPreExecute();
}
// create the http request
HttpWebRequest httpWebRequest = WebRequest.CreateHttp(this.Url);
httpWebRequest.Method = "GET";
httpWebRequest.Accept = "application/json";
// get the response asynchronously
httpWebRequest.BeginGetResponse(OnGetResponseCompleted, httpWebRequest);
}
private void OnGetResponseCompleted(IAsyncResult ar)
{
MessageBox.Show("We are in the OnGetResponseCompleted Method");
var httpWebRequest = (HttpWebRequest)ar.AsyncState;
// get the response
HttpWebResponse response;
try
{
response = (HttpWebResponse)httpWebRequest.EndGetResponse(ar);
}
catch (WebException e)
{
this.InvokeOnErrorHandler("Unable to connect to the web page.");
return;
}
catch (Exception e)
{
this.InvokeOnErrorHandler(e.Message);
return;
}
if (response.StatusCode != HttpStatusCode.OK)
{
this.InvokeOnErrorHandler((int)response.StatusCode + " " + response.StatusDescription);
return;
}
// response stream
var stream = response.GetResponseStream();
// deserialize json
var jsonSerializer = new DataContractJsonSerializer(typeof(T));
var responseObject = (T)jsonSerializer.ReadObject(stream);
// call the virtual method
this.InvokeInUiThread(() => this.OnPostExecute(responseObject));
}
The following are the DataContract classes I am using.
[DataContract]
public class OwnersList
{
public List<Owner> Owners {get; set; }
}
[DataContract]
public class Owner
{
[DataMember(Name = "oid")]
public string Oid { get; set; }
[DataMember(Name = "fname")]
public string Fname { get; set; }
[DataMember(Name = "lname")]
public string Lname { get; set; }
}
The following is a sample of te JSON data I am trying to deserialize.
[{"oid":"1","fname":"John","lname":"Doe"},{"oid":"2","fname":"Mary","lname":"Smith"},{"oid":"3","fname":"Jimi","lname":"Hendrix"},{"oid":"4","fname":"Carole","lname":"King"},{"oid":"5","fname":"John","lname":"Winchester"},{"oid":"6","fname":"John","lname":"Hurt"},{"oid":"7","fname":"Rick","lname":"Grimes"},{"oid":"8","fname":"Haris","lname":"Okic"},{"oid":"9","fname":"Dino ","lname":"Okic"},{"oid":"10","fname":"Mirza","lname":"Cirkic"}]
When I run my app, I get an Invalid Casting Exception either when creating the serializer object, or on the jsonserializer.ReadObject(stream) line. Any ideas as to why this is happening?

Parse twitter link with json.net

I need to obtain several pieces of information from a tweet using the json twitter API.
The only source provided is a tweet link.
This solution requires no twitter authentication and only 1 library json.net (available in Nuget Package Manager)
So far:
The program is able to do a httprequest on the Twitter json API.
I can see a response in the stream
But I am not able to deserialize the json response into the class.
Where:
Place a breakpoint in line and You will see that json_data contains json.
MyTweet = JsonConvert.DeserializeObject(json_data);
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
namespace parsejson
{
class Program
{
static void Main(string[] args)
{
try
{
Tweet MyTweet = new Tweet();
string url;
url = "https://api.twitter.com/1/statuses/oembed.json?url=https://twitter.com/katyperry/status/657469411700244480";
var json_data = string.Empty;
HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
req.Method = WebRequestMethods.Http.Get;
req.Accept = "application/json";
req.ContentType = "applicaton/json;charset=utf-8";
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader sr = new StreamReader(stream);
json_data = sr.ReadToEnd();
MyTweet = JsonConvert.DeserializeObject<Tweet>(json_data);
var stext = MyTweet.text;
Console.ReadLine();
}
catch (Exception)
{
throw;
}
}
public class Tweet
{
public string created_at { get; set; }
public long id { get; set; }
public string id_str { get; set; }
public string text { get; set; }
public string source { get; set; }
}
}
}

Request the access_token Instagram

I got the following problem:
I am trying to implement Instagram into my website. However I am stuck on the step where I need to get the Acces token. The api's documentation says I need to request it like this :
curl \-F 'client_id=CLIENT-ID' \
-F 'client_secret=CLIENT-SECRET' \
-F 'grant_type=authorization_code' \
-F 'redirect_uri=YOUR-REDIRECT-URI' \
-F 'code=CODE' \https://api.instagram.com/oauth/access_token
I use ASP.NET so I found this equivalent OAuth 2.0 In .NET With Instagram API:
NameValueCollection parameters = new NameValueCollection();
parameters.Add("client_id", "ssdfsdfsdfsdfsdf");
parameters.Add("client_secret", "sdsdfdsfsdfsdfsdfsdfsdf");
parameters.Add("grant_type", "authorization_code");
parameters.Add("redirect_uri", "http://localhost:2422/LoginsGuests/GetLoginPage");
parameters.Add("code", code);
WebClient client = new WebClient();
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", parameters);
var response = System.Text.Encoding.Default.GetString(result);
However I keep getting:
System.Net.WebException: The remote server returned an error: (400) Bad Request.
What I am i doing wrong?
Almost there the instagram api expects a POST not a GET.
Add the "POST" parameter.
var result = client.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
Also check the instagram settings -> redirect url.
Then this may help don't forget to add a reference to Newtonsoft.Json. Is in .Net version 4.5.1:
using System;
using System.Collections.Specialized;
using System.Net;
using System.Text;
namespace Instagram
{
public class InstagramClient
{
public InstagramClient(string code)
{
GetToken(code);
}
private void GetToken(string code)
{
using (var wb = new WebClient())
{
var parameters = new NameValueCollection
{
{"client_id", "ClientId"},
{"client_secret", "ClientSecret"},
{"grant_type", "authorization_code"},
{"redirect_uri", "RedirectUri"},
{"code", code}
};
var response = wb.UploadValues("https://api.instagram.com/oauth/access_token", "POST", parameters);
string json = Encoding.ASCII.GetString(response);
try
{
var OauthResponse = (InstagramOAuthResponse) Newtonsoft.Json.JsonConvert.DeserializeObject(json, typeof(InstagramOAuthResponse));
}
catch (Exception ex)
{
//handle ex if needed.
}
}
}
public class InstagramOAuthResponse
{
public string access_token { get; set; }
public User user { get; set; }
}
public class User : System.Security.Principal.IIdentity
{
public string username { get; set; }
public string website { get; set; }
public string profile_picture { get; set; }
public string full_name { get; set; }
public string bio { get; set; }
public string id { get; set; }
public string OAuthToken { get; set; }
public string AuthenticationType
{
get { return "Instagram"; }
}
public bool IsAuthenticated
{
get { return !string.IsNullOrEmpty(id); }
}
public string Name
{
get
{
return String.IsNullOrEmpty(full_name) ? "unknown" : full_name;
}
}
}
}
}
If you prefer HttpWebRequest class:
var request = (HttpWebRequest)WebRequest.Create("https://api.instagram.com/oauth/access_token/");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
var requestDetails = "client_id=" + AppConfig.InstagramClientId;
requestDetails += "&client_secret=" + AppConfig.InstagramClientSecret;
requestDetails += "&grant_type=authorization_code";
requestDetails += "&redirect_uri=" + redirectUrl;
requestDetails += "&code=" + exchangeCode;
byte[] bytes = Encoding.ASCII.GetBytes(requestDetails);
request.ContentLength = bytes.Length;
using (Stream outputStream = request.GetRequestStream())
{
outputStream.Write(bytes, 0, bytes.Length);
}
var response = request.GetResponse();
var code = ((HttpWebResponse)response).StatusCode;
if (code == HttpStatusCode.OK)
{
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
var jsonString = streamReader.ReadToEnd();
var accessToken = ParseAccessToken(jsonString);
return accessToken;
}
}

Categories

Resources