json parse from combobox data - json

want to parse a JSON string in combobox to 'text'. The response is something like
How can I parse the JSON and extract its 'text' values?
var restClient = new RestClient("https://cbsservis.tkgm.gov.tr/megsiswebapi.v2/api/idariYapi/ilListe");
var restRequest = new RestRequest(Method.GET);
var restResponse = restClient.Execute(restRequest);
restRequest.AddHeader("Accept", "text/json");
var jArray = Newtonsoft.Json.Linq.JObject.Parse(restResponse.Content);
dynamic jsonResponse = JsonConvert.DeserializeObject(restResponse.Content);
dynamic jsonResponse2 = JsonConvert.DeserializeObject<RootObject>(string JObject);`

Your response can be represented by classes like this:
public class Rootobject
{
public Feature[] features { get; set; }
public string type { get; set; }
public Crs crs { get; set; }
}
public class Crs
{
public string type { get; set; }
public Properties properties { get; set; }
}
public class Properties
{
public string name { get; set; }
}
public class Feature
{
public string type { get; set; }
public Geometry geometry { get; set; }
public Properties1 properties { get; set; }
}
public class Geometry
{
public string type { get; set; }
public object[][][] coordinates { get; set; }
}
public class Properties1
{
public string text { get; set; }
public int id { get; set; }
}
Hence your code can be changed to:
var restClient = new RestClient("https://cbsservis.tkgm.gov.tr/megsiswebapi.v2/api/idariYapi/ilListe");
var restRequest = new RestRequest(Method.GET);
var restResponse = restClient.Execute(restRequest);
restRequest.AddHeader("Accept", "text/json");
var obj = JsonConvert.DeserializeObject<Rootobject>(restResponse.Content);
You will receive the object like this:
And then you can loop through properties to get desired text.

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

Can't get API input list and convert it to json and get its contents

I have an API that as an input I have:
myMedicineJsonList=[{"medicineType":"ketamine","medicineDose":"5 drops","medicineDiode":"IV"},{"medicineType":"adrenaline","medicineDose":"5 drops","medicineDiode":"IV"}]
I need to get its contents and save it in a table in a database.
Currently I'm using the following code:
public partial class medicines
{
public int medicine{ get; set; }
public String medicineType { get; set; }
public String medicineDosage { get; set; }
public String medicinePlace { get; set; }
}
public System.Web.Http.Results.JsonResult<String> Insert_call_info( List<String> medicineList)
{
using (EMSMVCEntities entities = new EMSMVCEntities())
{
entities.Configuration.ProxyCreationEnabled = false;
try
{
var myMedicineJson = JsonConvert.SerializeObject(medicineList);
var myMedicineJsonList = JsonConvert.DeserializeObject<medicines>(myMedicineJson);
var medications = myMedicineJsonList.Value<JObject>("Medicine").ToObject<List<medicines>>();
var medicationsdb = entities.Set<Call_info_Medicines>();
...
}
}
}
However in myMedicineJsonList or in medications I can't get the contents of medicineList to store them in a table.
The table I want to store it is the following:
public partial class Call_info_Medicines
{
public int medicine_info_id { get; set; }
public string medicine { get; set; }
public string medicineType { get; set; }
public string medicineDosage { get; set; }
public string medicinePlace { get; set; }
}
I need to store it using the following line is the previous code snipset.
var medicationsdb = entities.Set<Call_info_Medicines>();
I found the following solution:
public class RootObject
{
public List<medicines> Medicine { get; set; }
}
var medResult = JsonConvert.DeserializeObject<RootObject>(medicineList);
var medicineTypeL = medResult.Medicine.Select(p => p.medicineType).ToList();
var medicineDosageL = medResult.Medicine.Select(p => p.medicineDosage).ToList();
var medicinePlaceL = medResult.Medicine.Select(p => p.medicinePlace).ToList();

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

Deserialize OneNote Notebooks API Response

I'm getting an empty object when I try to Deserialize a OneNote GetAllNotebooks query.
string[] tempCapture = null;
var url = new Uri("https://graph.microsoft.com/v1.0/me/onenote/notebooks");
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
if (IsAuthenticated)
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authResult.AccessToken);
}
var response = await client.GetAsync(url);
var result = await response.Content.ReadAsStringAsync();
tbResponse.Text = result.ToString();
DataContractJsonSerializer ser1 = new DataContractJsonSerializer(typeof(List<Value>));
MemoryStream stream1 = new MemoryStream(Encoding.UTF8.GetBytes(tbResponse.Text.ToString()));
var obj1 = (List<Value>)ser1.ReadObject(stream1);
I'm trying to get a list of notebooks, names, links to add to a database. And my table structure matches the class below.
Here is my OneNote API class
public class Value
{
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
public string name { get; set; }
public string self { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public string id { get; set; }
public string createdTime { get; set; }
}
Here is my new code with the RootObject. I'm still getting an error. It is in the catch exception.
var test = await client.GetAsync(url);
string testStr = await test.Content.ReadAsStringAsync();
DataContractJsonSerializer serial = new DataContractJsonSerializer(typeof(RootObject));
MemoryStream testStream = new MemoryStream(Encoding.UTF8.GetBytes(testStr));
try
{
var objx = (List<RootObject>)serial.ReadObject(testStream);
}
catch(Exception ex)
{
ex.ToString();
//"There was an error deserializing the object of type OneNoteSOAP2.RootObject. End element 'createdBy' from namespace '' expected. Found element 'user' from namespace ''."
}
You can use http://json2csharp.com/. Basically, just copy the value of our JSON being returned, and use the classes generated by this website. Use RootObject to deserialize.
I ran this for you and obtained these classes:
public class OneNoteClientUrl
{
public string href { get; set; }
}
public class OneNoteWebUrl
{
public string href { get; set; }
}
public class Links
{
public OneNoteClientUrl oneNoteClientUrl { get; set; }
public OneNoteWebUrl oneNoteWebUrl { get; set; }
}
public class Value
{
public string id { get; set; }
public string self { get; set; }
public string createdTime { get; set; }
public string name { get; set; }
public string createdBy { get; set; }
public string lastModifiedBy { get; set; }
public string lastModifiedTime { get; set; }
public bool isDefault { get; set; }
public string userRole { get; set; }
public bool isShared { get; set; }
public string sectionsUrl { get; set; }
public string sectionGroupsUrl { get; set; }
public Links links { get; set; }
}
public class RootObject
{
public List<Value> value { get; set; }
}

{"No parameterless constructor defined for type of 'System.String[]'."} while deserailsing json data

This is my controller
[NoCache]
public ActionResult SaveAssociate(string data)
{
JavaScriptSerializer json = new JavaScriptSerializer();
List<string> mystring = json.Deserialize<List<string>>(data);
return Content("Hai");
}
Expression data
value :
[{"AssetName":"8888","AssetNumber":"8888","Classification":null,"ParentAsset":null,"SerialNumber":"8888","ParentCompany":"JPL Holdings","Barcode":null,"RFIDTags":null,"AssetId":"dfe2ae51-f153-4a67-bd3b-0114d8a40751","Notes":null,"Manufacturer":null,"DepartmentId":null,"Department":null,"SupplierId":null,"Supplier":null},{"AssetName":"552014","AssetNumber":"552014","Classification":null,"ParentAsset":"8888","SerialNumber":"552014","ParentCompany":"JPL Holdings","Barcode":null,"RFIDTags":null,"AssetId":"4109ba40-af78-486a-a40e-1d14a2d7b42f","Notes":null,"Manufacturer":null,"DepartmentId":null,"Department":null,"SupplierId":null,"Supplier":null},{"AssetName":"201","AssetNumber":"201","Classification":null,"ParentAsset":null,"SerialNumber":"2011","ParentCompany":"JPL Holdings","Barcode":null,"RFIDTags":null,"AssetId":"3e552280-16df-4c17-a4a5-1f61c4c96835","Notes":null,"Manufacturer":null,"DepartmentId":null,"Department":null,"SupplierId":null,"Supplier":null}]
At this line List<string> mystring = json.Deserialize<List<string>>(data);
am getting
{"No parameterless constructor defined for type of 'System.String[]'."}
even i tried like this
[Serializable]
public class GetUser
{
public GetUserdata[] Data { get; set; }
}
[Serializable]
public class GetUserdata
{
public string AssetName { get; set; }
public string AssetNumber { get; set; }
public string Classification { get; set; }
public string ParentAsset { get; set; }
public string SerialNumber { get; set; }
public string ParentCompany { get; set; }
public string Barcode { get; set; }
public string RFIDTags { get; set; }
public string AssetId { get; set; }
public string Notes { get; set; }
public string Manufacturer { get; set; }
public string DepartmentId { get; set; }
public string Department { get; set; }
public string SupplierId { get; set; }
public string Supplier { get; set; }
}
controller
public ActionResult SaveAssociate(string data)
{
JavaScriptSerializer json = new JavaScriptSerializer();
GetUser mystring = json.Deserialize<GetUser>(data);
return Content("Hai");
}
Am getting error
Type 'AssetTrackingSystem.Model.GetUser' is not supported for deserialization of an array.
Help me
Instead of the above code, could you try:
public ActionResult SaveAssociate(string data)
{
JavaScriptSerializer json = new JavaScriptSerializer();
GetUserdata[] myUsers = json.Deserialize<GetUserdata[]>(data);
return Content("Hai");
}
Because your Json is sent as an array of object not an object of array.
I hope it will help you.