Bind JSON webservice in list View - json

I need to bind the json webservice into my list view adapter. I am getting error. Need to bind those values in the List View
[Activity(Label = "ListView", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
private ListView mListView;
public virtual IListAdapter ListAdapter { get; set; }
private List<RootObject> mUsers;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
mListView = FindViewById<ListView>(Resource.Id.listView1);
var url = "https://www.yellowbox.com.sg/index.php?route=api/app/getusers";
// Syncronious Consumption
var syncClient = new WebClient();
var content = syncClient.DownloadString(url);
var TEST = JsonConvert.DeserializeObject <RootObject>(content);
// getting null values in "TEST"
//mUsers =????
ListAdapter = new ArrayAdapter<RootObject>(this, Android.Resource.Layout.SimpleListItem1, mUsers);
mListView.Adapter = ListAdapter;
}
My class:
public class RootObject
{
public string id { get; set; }
public string username { get; set; }
public string total_deliveries { get; set; }
}

Related

How can I implement JSON file into a drop down list for countries in a validation form?

I tried with this code, but it doesn't seem to work.
public ActionResult Getcountries()
{
var webClient = new WebClient();
var json = webClient.DownloadString(#"C:\Users\kristijanm\source\repos\contactForm\contactForm\data\Countries.json");
var CountryL = JsonConvert.DeserializeObject<CountriesModel>(json);
return View(CountryL);
}
Here is my Model:
public class CountriesModel
{
public int Id { get; set; }
public string Code { get; set; }
public string Name { get; set; }
}
}

RestSharp query returning NotFound

This is my first usage of RestSharp
I am trying to connect to HubSpot using their FormsAPI (https://legacydocs.hubspot.com/docs/methods/forms/submit_form)
Using .Net, C#, MVC.
When I run in Fiddler, it works.
Here is my C# code, when I run it, I get a StatusCode of "NotFound". I am sure it is something simple I am missing?
var client = new RestClient("https://api.hsforms.com");
var request = new RestRequest("submissions/v3/integration/submit/{PortalId}/{formGuid}", Method.POST);
request.AddUrlSegment("portalId", "[myportalid]");
request.AddUrlSegment("formGuid", "[myformid]");
request.AddQueryParameter("hapikey", "[myapikey]");
request.RequestFormat = DataFormat.Json;
request.AddParameter("firstname", "testfirstname");
request.AddParameter("lastname", "testlastname");
request.AddParameter("email", "testemail#emailaddress.com");
request.AddParameter("business_unit", "Test");
It is better to create model of c# class and serialize it to Json and send POST request.
Example of RestSharp request
public async Task SendHubSpotRequest()
{
var PortalId = 1;
var formGuid = 1;
var client = new RestClient("https://api.hsforms.com");
var request = new RestRequest($"submissions/v3/integration/submit/{PortalId}/{formGuid}", Method.POST);
var hubSpotRequest = new HubSpotRequest()
{
SubmittedAt = "1517927174000",
Fields = new Field[]
{
new Field() { Name = "email", Value = "testemail#emailaddress.com" },
new Field() { Name = "firstname", Value = "testfirstname" },
new Field() { Name = "lastname", Value = "testlastname" }
},
Context = new Context
{
Hutk = "hutk",
PageUri = "www.example.com/page",
PageName = "Example page"
},
LegalConsentOptions = new LegalConsentOptions
{
Consent = new Consent
{
// Fill other params
}
}
};
request.AddParameter("application/json; charset=utf-8", JsonConvert.SerializeObject(hubSpotRequest), ParameterType.RequestBody);
var response = await client.ExecuteAsync(request);
var responseContent = response.Content;
}
C# classes of body json model
public class HubSpotRequest
{
[JsonProperty("submittedAt")]
public string SubmittedAt { get; set; }
[JsonProperty("fields")]
public Field[] Fields { get; set; }
[JsonProperty("context")]
public Context Context { get; set; }
[JsonProperty("legalConsentOptions")]
public LegalConsentOptions LegalConsentOptions { get; set; }
}
public class Context
{
[JsonProperty("hutk")]
public string Hutk { get; set; }
[JsonProperty("pageUri")]
public string PageUri { get; set; }
[JsonProperty("pageName")]
public string PageName { get; set; }
}
public class Field
{
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("value")]
public string Value { get; set; }
}
public class LegalConsentOptions
{
[JsonProperty("consent")]
public Consent Consent { get; set; }
}
public class Consent
{
[JsonProperty("consentToProcess")]
public bool ConsentToProcess { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
[JsonProperty("communications")]
public Communication[] Communications { get; set; }
}
public class Communication
{
[JsonProperty("value")]
public bool Value { get; set; }
[JsonProperty("subscriptionTypeId")]
public long SubscriptionTypeId { get; set; }
[JsonProperty("text")]
public string Text { get; set; }
}

Deserialize JSON data in to a class in c#

hello people I have this Json data:
https://openexchangerates.org/api/latest.json?app_id=6cf59607a32d408eb3e04de1427a3169
and I want to deserialize in the following class
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Divisas2MVVM2.Classes
{
public class ExchangeRates
{
[JsonProperty(PropertyName = "disclaimer")]
public string Disclaimer { get; set; }
[JsonProperty(PropertyName = "license")]
public string License { get; set; }
[JsonProperty(PropertyName = "timestamp")]
public int TimeStamp { get; set; }
[JsonProperty(PropertyName = "base")]
public string Base { get; set; }
[JsonProperty(PropertyName = "rates")]
public Rates Rates { get; set; }
}
public class Rates
{
public double AED { get; set; }
public double AFN { get; set; }
public double ALL { get; set; }
public double AMD { get; set; }
// I cut the text so that it would not be to long
public double ZMW { get; set; }
public double ZWL { get; set; }
}
public class Rate
{
public double TaxRate { get; set; }
public string Code { get; set; }
}
this is my attribute
private ExchangeRates exchangeRates;
the constructor of my MainViewModel
new ObservableCollection data
Rates = new ObservableCollection<Rate>();
and in this method a get the json data
try
{
var client = new HttpClient();
client.BaseAddress = new Uri("https://openexchangerates.org");
var url = "/api/latest.json?app_id=6cf59607a32d408eb3e04de1427a3169";
var response = await client.GetAsync(url);
if (!response.IsSuccessStatusCode)
{
Message = response.StatusCode.ToString();
IsRunning = false;
return;
}
var result = await response.Content.ReadAsStringAsync();
exchangeRates = JsonConvert.DeserializeObject<ExchangeRates>(result);
}
everything works fine, the variable result has correctly the json data in a string format, but when i call JsonConvert . DeserializeObject, the data "rates" it is not assigned correctly, all the other data: disclaimer", "license", "timestamp" etc. is correctly assigned. only rates fail.
the string is correct
other data is correct in the class
rates is incorrect
sorry for my English I hope you have understood me :)
use this as your model class
namespace Rate
{
using System;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
public partial class Rates
{
[JsonProperty("disclaimer")]
public string Disclaimer { get; set; }
[JsonProperty("license")]
public string License { get; set; }
[JsonProperty("timestamp")]
public long Timestamp { get; set; }
[JsonProperty("base")]
public string Base { get; set; }
[JsonProperty("rates")]
public Dictionary<string, double> RatesRates { get; set; }
}
public partial class Rates
{
public static Rates FromJson(string json) => JsonConvert.DeserializeObject<Rates>(json, Rate.Converter.Settings);
}
public static class Serialize
{
public static string ToJson(this Rates self) => JsonConvert.SerializeObject(self, Rate.Converter.Settings);
}
internal static class Converter
{
public static readonly JsonSerializerSettings Settings = new JsonSerializerSettings
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
DateParseHandling = DateParseHandling.None,
Converters = {
new IsoDateTimeConverter { DateTimeStyles = DateTimeStyles.AssumeUniversal }
},
};
}
}
Then do this in your class
var data = Rate.Rates.FromJson("jsonresult");
var rate = data.RatesRates;
foreach (var pair in rate)
{
string symbol = pair.Key; //"AED"
double value = pair.Value; //3.673175,
}
var time = data.Timestamp;
var disclaimer = data.Disclaimer;
var license = data.License;
Tested and working

WP read user_id from JSON and show it

I want to show user_id from the following JSON:
[{"username":"Kac26","email":"xklemenx#gmail.com","city":"Slovenj Gradec","id":"15"}]
So I save this JSON to class. I get JSON from my webpage.
My class:
public class Class2
{
public string username{ get; set; }
public string email { get; set; }
public string city { get; set; }
public int id { get; set; }
}
Saving JSON to class:
private async void Login_Tapped(object sender, TappedRoutedEventArgs e)
{
string str = user.Text; //get user name from textbox
HttpClient http = new HttpClient();
var response= await http.GetStringAsync("http://mywebpage.com/events/apis/user.php/user=" + str);
}
Then I want to show user id in textbox_id when i press button.
private void Button_Tapped(object sender, TappedRoutedEventArgs e)
{
textbox_id.Text = Class2.id;
}
But error shows up when I try to reach Class2.id
Anyone know how to do that? And do I save json to class correct?
Thanks!!!
In "Saving JSON to class", I don't see where you are actually doing that. Here's how you would deserialize the string returned by the service:
private async void Login_Tapped(object sender, TappedRoutedEventArgs e)
{
string str = user.Text; //get user name from textbox
HttpClient http = new HttpClient();
var response = await http.GetStringAsync("http://mywebpage.com/events/apis/user.php/user=" + str);
Class2 myClass2 = null;
try
{
var jsonSerializer = new DataContractJsonSerializer(typeof(Class2));
using (var stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(response)))
{
myClass2 = jsonSerializer.ReadObject(stream) as Class2;
}
}
catch
{
// serialization error occurred
}
// do something with myClass2
}
Also, FYI if you don't want the property names on your response class to match the JSON properties (for example, not be lower case), you can use DataContractAttribute and DataMemberAttribute on your class like so:
[DataContract]
public class Class2
{
[DataMember(name = "username")]
public string UserName { get; set; }
[DataMember(name = "email")]
public string EMail { get; set; }
[DataMember(name = "city")]
public string SomeCompletelyDifferentNameForCity { get; set; }
[DataMember(name = "id")]
public int Id { get; set; }
}
Class2.id is a static access to a non-static property of Class2. You have to create an instance of Class2 with new Class2(); at some point and then you can access the property.

Parsing complex JSON

I want to parse a complex JSON on WP7. First I have to parse a JSON feed and I retrieve data to parse second JSON feed.
To parse the first feed I use this web service
http://horaires-ter-sncf.naholyr.fr/prochainsdeparts.php?gare=...
after that we use the code and the station's name to parse the second feed
http://horaires-ter-sncf.naholyr.fr/prochainsdeparts.php?gare=....&id=...
This my code but it doesn't work:
public static class Parser
{
public static string resultats;
public static reponse[] obj = new reponse[]{new reponse(),new reponse()};
public static reponse1 obj1 = new reponse1();
public static void HttpsCompleted_reponse(object sender, DownloadStringCompletedEventArgs e)
{
Horaire hre =new Horaire();
try
{
var ms = new MemoryStream(Encoding.Unicode.GetBytes(resultats));
var ser = new DataContractJsonSerializer(typeof(reponse1));
obj1 = (reponse1)ser.ReadObject(ms);
}
catch
{
WebClient wc = new WebClient();
//wc.DownloadStringCompleted += HttpsCompleted_reponse1;
wc.DownloadStringAsync(new Uri("http://horaires-ter-sncf.naholyr.fr/prochainsdeparts.php?gare=" +hre.gettxt()));
Debug.WriteLine("youuuuuuuuuuuuuuuuuuuuuuuppppppppppiiii");
}
}
/*
public static void HttpsCompleted_reponse1(object sender, DownloadStringCompletedEventArgs e)
{
try
{
var ms = new MemoryStream(Encoding.Unicode.GetBytes(resultats));
var ser = new DataContractJsonSerializer(typeof(Gare));
obj1 = (reponse1)ser.ReadObject(ms);
}
catch
{
WebClient wc = new WebClient();
wc.DownloadStringCompleted += HttpsCompleted_reponse;
wc.DownloadStringAsync(new Uri("http://horaires-ter-sncf.naholyr.fr/prochainsdeparts.php?gare=" + obj.success.Gares.Eleme + "&id=" + obj.success.id));
}
}
*/
}
public class Depart
{
[DataMember(Name = "type")]
public string type { get; set; }
[DataMember(Name = "heure")]
public string heure { get; set; }
[DataMember(Name = "destination")]
public string destination { get; set; }
[DataMember(Name="attention")]
public string attention { get; set; }
[DataMember(Name = "retards")]
public string [] retards { get; set; }
[DataMember(Name = "source")]
public string source { get; set; }
public Depart()
{
}
}
public class Success {
[DataMember(Name = "nom")]
public string nom { get; set; }
[DataMember(Name = "id")]
public int id { get; set; }
[DataMember(Name = "departs")]
public Depart[] departs { get; set; }
public Success()
{
this.departs = new Depart[0];
}
}
public class Success1
{
[DataMember(Name="Gares")]
public Gare[] Gares { get; set; }
public Success1()
{
this.Gares = new Gare[0];
}
}
public class Gare{
[DataMember(Name="Nom")]
public string Nom { get; set; }
[DataMember(Name="code")]
public int code { get; set; }
public Gare()
{
}
}
public class reponse
{
[DataMember(Name = "code")]
public string code{get;set;}
[DataMember(Name = "success")]
public Success1 success{get;set;}
public reponse()
{
this.success = new Success1();
}
}
public class reponse1 {
[DataMember(Name = "code")]
public string code { get; set; }
[DataMember(Name = "success")]
public Success success { get; set; }
public reponse1()
{
this.success = new Success();
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
//for (int i=0; i<=Parser.obj1.Length;i++)
Debug.WriteLine(Parser.obj1.success.nom);
}
}
There are several problems in your code. But even if you solved them you wouldn't be able to parse the list of received stations with DataContractJsonSerializer out of the box.
Explanation:
The web site offering the web service you are using says a response from your first "JSON feed" looks like this:
{"code":201,"success":{"gares":{"villefranche-d''alb.-ce":1750,"villefranche
de rgue-12":1749,...}}}
Have a look at the stations and their IDs:
{"villefranche-d''alb.-ce":1750,"villefranche de rgue-12":1749,...}
This is an associative array where the keys and values are not explicitly decorated with "Key" and "Value". But these decorations are necessary for DataContractJsonSerializer to parse the JSON. They would have to be in format
[{“Key”:“villefranche-d''alb.-ce”,“Value”:“1750”},{“Key”:“villefranche
de rgue-12”,“Value”:“1749”}]
to be properly parsed by DataContractJsonSerializer. (The reason is that this serializer supports more complex types than int and string to be used as keys and values.)
This blog post contains a very good description of the matter and how JavaScriptSerializer could be the solution. But unfortunately this class isn't available in Silverlight.
More people having similar problems like you:
Deserialization problem with DataContractJsonSerializer
.NET: Can I use DataContractJsonSerializer to serialize to a JSON associative array?
https://json.codeplex.com/discussions/258083
https://connect.microsoft.com/VisualStudio/feedback/details/558686/
Solution:
Use Json.NET.
Have a look at json.NET, it should provide you with linq2json and a simple serialise to object.