Xamarin - reading JSON file and reading the values - xamarin

everyone ! I'm new in Xamarin. I've this json file...
{
"debug":true,
"sequence":[
"p1"
],
"pages":[
{
"pageId":"p1",
"type":"seq",
"elements":[
{
"type":"smallVideo",
"width":300,
"height":300,
"top":0,
"left":0,
"file":"xxx.mp4"
}
]
}
],
"index":[
{
"width":300,
"height":300,
"top":0,
"left":0,
"goTo":"p1"
}
]
}
And this is my simple code...
using Newtonsoft.Json;
JObject elements = JObject.Parse(File.ReadAllText("elements.json"));
Console.WriteLine(elements);
Ok, I can see on my output screen the whole JSON file. Fine...
But I'd like to read any value just like javascript, examples...
elements.debug (true)
elements.pages[0].pageId
So, I need to retrieve values based on the key/path like it's usual in Javascript. Any clue ?
ty !

C# is a little bit different from js, here you need to declare objects.
In your case you need to create new class called ElementsObj and your object would be this class instance:
public class ElementsObj
{
public bool debug { get; set; }
public List<string> sequence { get; set; }
public List<Page> pages { get; set; }
public List<Index> index { get; set; }
}
public class Element
{
public string type { get; set; }
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string file { get; set; }
}
public class Page
{
public string pageId { get; set; }
public string type { get; set; }
public List<Element> elements { get; set; }
}
public class Index
{
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string goTo { get; set; }
}
In future use http://json2csharp.com/ to generate classes from JSON file.
Later you can deserialize your JSON to this object.
I'd suggest Newtonsoft lib to do this:
ElementsObj tmp = JsonConvert.DeserializeObject<ElementsObj>(jsonString);

1) Option create an object that reflects your JSON structure:
public class Element
{
public string type { get; set; }
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string file { get; set; }
}
public class Page
{
public string pageId { get; set; }
public string type { get; set; }
public List<Element> elements { get; set; }
}
public class Index
{
public int width { get; set; }
public int height { get; set; }
public int top { get; set; }
public int left { get; set; }
public string goTo { get; set; }
}
public class MyObject
{
public bool debug { get; set; }
public List<string> sequence { get; set; }
public List<Page> pages { get; set; }
public List<Index> index { get; set; }
}
MyObject parsed = JsonConvert.DeserializeObject<MyObject>(File.ReadAllText("elements.json"));
var debug = parsed.debug;
2) Option using dynamic
dynamic results = JsonConvert.DeserializeObject<dynamic>(File.ReadAllText("elements.json"));
var debug = dynamic.debug;

Related

Parsing a google directions json

I am working with google directions Api...But I am facing problems for read the Json response...Does Someone know about this Api and can help me?
I need get all route points to draw my polyline...which datas is important to get for it? How can I receive and parse it?
This is a json as example
https://maps.googleapis.com/maps/api/directions/json?origin=-22.8895625,-47.0714089&destination=-22.892376,-47.027553&key=
my code that doesn't work...
public static async Task<List<Model.Localizacao>> GetDirectionsAsync(Localizacao locUser, Localizacao locLoja)
{
using (var client = new HttpClient())
{
try
{
List<Model.Localizacao> lstLoc = new List<Model.Localizacao>();
var json = await client.GetStringAsync("https://maps.googleapis.com/maps/api/directions/json?origin=" + locUser.latitude + "," + locUser.longitude + "&destination="+ locLoja.latitude+","+locLoja.longitude+"&key="+ GOOGLEMAPSKEY);
// json = json.Substring(json.IndexOf('['));
// json = json.Substring(0, json.LastIndexOf(']') + 1);
lstLoc = JsonConvert.DeserializeObject<List<Model.Localizacao>>(json);
return lstLoc;
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
return null;
}
}
}
I really need a help
I have searched and the results hasn't helped me yet
its a xamarin forms project
Thank you
Don't try to pull out part of the json, deserialize the whole thing and grab the data you need from the C# object graph.
You can use json2csharp.com to generate a C# class structure.
I pasted in the json you linked to and it generated the following:
public class GeocodedWaypoint
{
public string geocoder_status { get; set; }
public string place_id { get; set; }
public List<string> types { get; set; }
}
public class Northeast
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Southwest
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Bounds
{
public Northeast northeast { get; set; }
public Southwest southwest { get; set; }
}
public class Distance
{
public string text { get; set; }
public int value { get; set; }
}
public class Duration
{
public string text { get; set; }
public int value { get; set; }
}
public class EndLocation
{
public double lat { get; set; }
public double lng { get; set; }
}
public class StartLocation
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Distance2
{
public string text { get; set; }
public int value { get; set; }
}
public class Duration2
{
public string text { get; set; }
public int value { get; set; }
}
public class EndLocation2
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Polyline
{
public string points { get; set; }
}
public class StartLocation2
{
public double lat { get; set; }
public double lng { get; set; }
}
public class Step
{
public Distance2 distance { get; set; }
public Duration2 duration { get; set; }
public EndLocation2 end_location { get; set; }
public string html_instructions { get; set; }
public Polyline polyline { get; set; }
public StartLocation2 start_location { get; set; }
public string travel_mode { get; set; }
public string maneuver { get; set; }
}
public class Leg
{
public Distance distance { get; set; }
public Duration duration { get; set; }
public string end_address { get; set; }
public EndLocation end_location { get; set; }
public string start_address { get; set; }
public StartLocation start_location { get; set; }
public List<Step> steps { get; set; }
public List<object> traffic_speed_entry { get; set; }
public List<object> via_waypoint { get; set; }
}
public class OverviewPolyline
{
public string points { get; set; }
}
public class Route
{
public Bounds bounds { get; set; }
public string copyrights { get; set; }
public List<Leg> legs { get; set; }
public OverviewPolyline overview_polyline { get; set; }
public string summary { get; set; }
public List<object> warnings { get; set; }
public List<object> waypoint_order { get; set; }
}
public class RootObject
{
public List<GeocodedWaypoint> geocoded_waypoints { get; set; }
public List<Route> routes { get; set; }
public string status { get; set; }
}

Microsoft Cognitive Services Web Search API - DeSerialization Issues

I want to learn Cognitive Services Web Search APIs so I started creating a bot application . I already have a account sub- key and other required information also I read many articles and watch build 2016 videos on this as well.I am having trouble while deserializing the result .
I am not able to find the proxy class that I can use to do that .
The url I am using is https://api.cognitive.microsoft.com/bing/v5.0/search/
and I found a proxy class for previous api version . Can anybody tell me how to get proxy class of the api request / response in VS 2015 for these service.
My Code look like this:
string BingSearchUrl = "https://api.cognitive.microsoft.com/bing/v5.0/search/";
const string bingKey = "Key";
public static async Task<string> Search(string query)
{
var client = HttpClientFactory.Create();
var queryString = BingSearchUrl + "?q=" + query + "&count=10";
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", bingKey);
client.DefaultRequestHeaders.Add("Accept", "application/json");
// Request parameters
string r = await client.GetStringAsync(queryString);
var jsonResult = JsonConvert.DeserializeObject<Bing.ExpandableSearchResult>(r);
return jsonResult.Web.First().Title;
Try below code
public string BingSearchUrl = "https://api.cognitive.microsoft.com/bing/v5.0/search/";
const string bingKey =[KEY];
public async void Search()
{
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", bingKey);
// Request parameters
queryString["q"] = "microsoft";
queryString["count"] = "10";
queryString["offset"] = "0";
queryString["mkt"] = "en-us";
queryString["safeSearch"] = "Moderate";
var uri = "https://api.cognitive.microsoft.com/bing/v5.0/news/search?" + queryString;
var response = await client.GetStringAsync(uri);
var jsonResult = JsonConvert.DeserializeObject<BingJson>(response);
string title = jsonResult.value[0].name.ToString();
}
With the jsonResult.value[0] you can loop through the results. First results is at [0] position.
I Created a model class looking at the bing search response json. It looks like,
public class BingJson
{
public string _type { get; set; }
public Instrumentation instrumentation { get; set; }
public string readLink { get; set; }
public int totalEstimatedMatches { get; set; }
public Value[] value { get; set; }
}
public class Instrumentation
{
public string pingUrlBase { get; set; }
public string pageLoadPingUrl { get; set; }
}
public class Value
{
public string name { get; set; }
public string url { get; set; }
public string urlPingSuffix { get; set; }
public Image image { get; set; }
public string description { get; set; }
public About[] about { get; set; }
public Provider[] provider { get; set; }
public DateTime datePublished { get; set; }
public string category { get; set; }
}
public class Image
{
public Thumbnail thumbnail { get; set; }
}
public class Thumbnail
{
public string contentUrl { get; set; }
public int width { get; set; }
public int height { get; set; }
}
public class About
{
public string readLink { get; set; }
public string name { get; set; }
}
public class Provider
{
public string _type { get; set; }
public string name { get; set; }
}
With this model, I am able to get the desired result. The Model which is presented in the other answer is not working in my case.
namespace BingSearchBot
{
public class RootObject
{
public string _type { get; set; }
public WebPages webPages { get; set; }
public RelatedSearches relatedSearches { get; set; }
public RankingResponse rankingResponse { get; set; }
}
public class WebPages
{
public string webSearchUrl { get; set; }
public int totalEstimatedMatches { get; set; }
public List<Value> value { get; set; }
}
public class Value
{
public string id { get; set; }
public string name { get; set; }
public string url { get; set; }
public List<About> about { get; set; }
public string displayUrl { get; set; }
public string snippet { get; set; }
public List<DeepLink> deepLinks { get; set; }
public string dateLastCrawled { get; set; }
public List<SearchTag> searchTags { get; set; }
}
public class About
{
public string name { get; set; }
}
public class DeepLink
{
public string name { get; set; }
public string url { get; set; }
public string snippet { get; set; }
}
public class SearchTag
{
public string name { get; set; }
public string content { get; set; }
}
public class Value2
{
public string text { get; set; }
public string displayText { get; set; }
public string webSearchUrl { get; set; }
}
public class RelatedSearches
{
public string id { get; set; }
public List<Value2> value { get; set; }
}
public class Value3
{
public string id { get; set; }
}
public class Item
{
public string answerType { get; set; }
public int resultIndex { get; set; }
public Value3 value { get; set; }
}
public class Mainline
{
public List<Item> items { get; set; }
}
public class RankingResponse
{
public Mainline mainline { get; set; }
}
}

Using Linq to populate a class

I am getting a weird behavior. I have a class that I created that is used to format data comping from a data entity into a data grid. I am a using a linq query to create a list of the class type from a list of the entity type. Some of the properties of the class are accessible from the linq query but other give me an error. (AMNotStartedPortalDisplay' does not contain a definition for 'ChecklistStatusID'). So my question is why can linq access some properties but not others? I see no reason why this should be happening.
Here is my class:
public class AMWOTPortalDisplay
{
public string DisplayName { get; set; }
public string LOB { get; set; }
public string DisplayProjectPackages { get; set; }
public string ChecklistStatus { get; set; }
public int ChecklistStatusID { get; set; }
public string InstallDate { get; set; }
public string dateToYellow { get; set; }
public string dateToRed { get; set; }
public string ApplicationManager { get; set; }
public string ApplicationManagerLanID { get; set; }
public int ApplicationManagerUserID { get; set; }
public string ImpersonatedManager { get; set; }
public string ImpersonatedManagerLanID { get; set; }
public int ImpersonatedManagerUserID { get; set; }
public string DelegateName { get; set; }
public string DelegateLanID { get; set; }
public int DelegateUserID { get; set; }
public string WOTAssignee { get; set; }
public int ChecklistID { get; set; }
public string DisplayLinkText { get; set; }
public string LinkTextURL { get; set; }
public string rowColor { get; set; }
public string rowTextColor { get; set; }
}
And here is the linq query as I have it so far:
var portaldisplay = checklists
.Select(c => new AMNotStartedPortalDisplay
{
DisplayName = string.Format("{0} ({1})", c.Application.Name, c.Application.ApplicationID),
LOB = c.Application.LOB,
ChecklistStatus = c.ChecklistStatusType.TypeName,
ChecklistStatusID = c.ChecklistStatusTypeID
});
Thanks,
Rhonda
Be careful with your types:
public class AMWOTPortalDisplay
And then:
Select(c => new AMNotStartedPortalDisplay { ... })
It looks like your query should probably be:
Select(c => new AMWOTPortalDisplay { ... })

RestSharp - WP7 - Cannot deserialize XML to a list

I use RestSharp in my Windows Phone 7.1 project.
I have a response in XML format here:
https://skydrive.live.com/redir.aspx?cid=0b39f4fbbb0489dd&resid=B39F4FBBB0489DD!139&parid=B39F4FBBB0489DD!103&authkey=!AOdT-FiS6Mw8v5Y
I tried to deserialize that response to a class:
public class fullWall
{
public _user user { get; set; }
public int numberOfFriend { get; set; }
public int numberOfPhoto { get; set; }
public List<timhotPhotos> timhotPhotos { get; set; }
public fullWall()
{
timhotPhotos = new List<timhotPhotos>();
}
}
All properties are ok except the timhotPhotos list, as you can see here:
timhotPhotos class:
public class timhotPhotos
{
public string id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string url { get; set; }
public double width { get; set; }
public double height { get; set; }
public DateTime createdDate { get; set; }
public _user user { get; set; }
public int numOfComment { get; set; }
public int numOfRate { get; set; }
public int numOfView { get; set; }
public bool rated { get; set; }
}
Where am I wrong?
You'll have to change the default XML deserializer to the DotNetXmlDeserializer, like this:
RestClient client;
client.AddHandler("application/xml", new DotNetXmlDeserializer());
Then, add the XmlElement attribute to the List<timhotPhotos> timhotPhotos property like this:
public class fullWall
{
public _user user { get; set; }
public int numberOfFriend { get; set; }
public int numberOfPhoto { get; set; }
[System.Xml.Serialization.XmlElement()]
public List<timhotPhotos> timhotPhotos { get; set; }
public fullWall()
{
timhotPhotos = new List<timhotPhotos>();
}
}
Now it should work fine!

reference model variable to global variable value in .net mvc3

with curiosity...
i am seeking for a temporary solution that will lead to an expansions of a system side controller.
i a mvc3.net razor based project with 100+ of class file
all of the class file (model) has a system field
specific
public string u_by { get; set; }
public System.DateTime u_date { get; set; }
public System.DateTime c_date { get; set; }
public string c_by { get; set; }
public int version { get; set;
public int groupid { get; set; }
public int status { get; set; }
at the moment the useraccess control has not been build yet which in the end the useraccess controller will and suppose to fill in this variable.
i need to fixed the value for all the variable above during a form insert, update, delete
is there any where i can
create a class and put a default value to it ?
i have created a
namespace webapp.Models
{
public class sysfield
{
public string _updatedBy;
public string _createdBy;
public DateTime _updatedDate;
public DateTime _createdDate;
public int _version;
public int _groupid;
public int _status;
//Constructor
public sysfield()
{
_updatedBy = HttpContext.Current.Server.MachineName.ToString();
_createdBy = HttpContext.Current.Server.MachineName.ToString();
_updatedDate = System.DateTime.Now;
_createdDate = System.DateTime.Now;
_version = updateVersion;
_groupid = 100;
_status = 1;
}
//Property
public int updateVersion
{
get
{
return _version;
}
set
{
_version = _version + 1;
}
}
//Set Values
public string createdBy(string initialCreator)
{
if (updateVersion == 1)
{
return _createdBy = initialCreator;
}
else
{
return _createdBy = HttpContext.Current.Server.MachineName.ToString();
}
}
public DateTime createdDate(DateTime initialDate)
{
if (updateVersion == 1)
{
return _createdDate = initialDate;
}
else
{
return _createdDate = System.DateTime.Now;
}
}
}
}
now the question is how do i default it in code below, where when i insert the model
of
namespace webapp.Models
{
public partial class usr_myapp
{
public int VEHID { get; set; }
public string CARNAME { get; set; }
public string CATEGORY { get; set; }
public string TYPE { get; set; }
public string u_by { get; set; }
public System.DateTime u_date { get; set; }
public System.DateTime c_date { get; set; }
public string c_by { get; set; }
public int version { get; set; }
public int groupid { get; set; }
public int status { get; set; }
}
}
with the Controller:
Where user will fill in everything else except for the system field c_by,u_by, and etc...
// POST: /myapp/Create
[HttpPost]
public ActionResult Create(usr_myapp usr_myapp)
{
if (ModelState.IsValid)
{
db.usr_myapp.Add(usr_myapp);
db.SaveChanges();
}
return View(usr_myapp);
}
how do i default the
`
public ActionResult Create(usr_myapp usr_myapp)
{
if (ModelState.IsValid)
{
db.usr_myapp.Add(usr_myapp);
db.SaveChanges();
}
return View(usr_myapp);
}
`
where usr_myapp consist of
public int VEHID { get; set; }
public string CARNAME { get; set; }
public string CATEGORY { get; set; }
public string TYPE { get; set; }
public string u_by { get; set; }
public System.DateTime u_date { get; set; }
public System.DateTime c_date { get; set; }
public string c_by { get; set; }
public int version { get; set; }
public int groupid { get; set; }
public int status { get; set; }
the partial class, i got it from the edmx generation should i be changing all of it?
a lost man in the amazing world
You set the defaults in the constructor. Do you have a specific need for it to be a partial class?

Resources