Parsing JSON error object containing an array with Windows Phone 7 - windows-phone-7

public class Restaurants1
{
public string id { get; set; }
public string name { get; set; }
public string address { get; set; }
public string contact { get; set; }
public string links { get; set; }
public string about { get; set; }
public string info { get; set; }
public string image { get; set; }
public string lat { get; set; }
public string lng { get; set; }
public string currency { get; set; }
public string minprice { get; set; }
public string maxprice { get; set; }
public string facility { get; set; }
public string keywords { get; set; }
public string status { get; set; }
public string review_count { get; set; }
public string distance { get; set; }
public string menu_image { get; set; }
public string menu_resizead { get; set; }
}
public class Restaurants2
{
public string id { get; set; }
public string name { get; set; }
public string address { get; set; }
public string contact { get; set; }
public string links { get; set; }
public string about { get; set; }
public string info { get; set; }
public string image { get; set; }
public string lat { get; set; }
public string lng { get; set; }
public string currency { get; set; }
public string minprice { get; set; }
public string maxprice { get; set; }
public string facility { get; set; }
public string keywords { get; set; }
public string status { get; set; }
public string review_count { get; set; }
public string distance { get; set; }
public string menu_image { get; set; }
public string menu_resizead { get; set; }
}
public class Result
{
public List<Restaurants1> restaurants1 { get; set; }
public List<Restaurants2> restaurants2 { get; set; }
public bool no_featured { get; set; }
}
public class RootObject
{
public string status { get; set; }
public Result result { get; set; }
}
var url = e.UserState as Uri;
RootObject root = JsonConvert.DeserializeObject<RootObject>(e.Result);
MessageBox.Show("success");
RootObject root = JsonConvert.DeserializeObject<RootObject>(e.Result) is Error
like this :
Error 1 The best overloaded method match for
'Newtonsoft.Json.JsonConvert.DeserializeObject(string)'
has some invalid
arguments E:\parsingjson\parsingjson\MainPage.xaml.cs 103 30 parsingjson
why?
and how to fix it ?

Post a snippet of your json containing at least one record. are you sure e.Result is of a string Type? If it is a stream then you would need to read the stream into a string using a StreamReader for the Json Deserializer to work.

Related

Web API JSON deserialization converting value issue

I am trying to insert JSON data into my models via EF 6. I am getting this error;
Inner Exception is {0}System.ArgumentException: Could not cast or convert from System.String to EPINMiddleWareAPI.Models.Serial.
konum: Newtonsoft.Json.Utilities.ConvertUtils.EnsureTypeAssignable(Object value, Type initialType, Type targetType)
konum: Newtonsoft.Json.Utilities.ConvertUtils.ConvertOrCast(Object initialValue, CultureInfo culture, Type targetType)
konum: Newtonsoft.Json.Serialization.JsonSerializerInternalReader.EnsureType(JsonReader reader, Object value, CultureInfo culture, JsonContract contract, Type targetType)
Message ---
{0}Error converting value "c57a55b5-b2d4-46e7-86e0-cc13726ca8a7" to type 'EPINMiddleWareAPI.Models.Serial'. Path 'coupons[0].serials[0]', line 1, position 310.
Here is my model structure:
public class ConfirmResponse
{
public int Id { get; set; }
public string referenceId { get; set; }
public string version { get; set; }
public string signature { get; set; }
public string paymentID { get; set; }
public string productCode { get; set; }
public string currency { get; set; }
public string ApplicationCode { get; set; }
public double unitPrice { get; set; }
public double totalPrice { get; set; }
public string purchaseStatusCode { get; set; }
public DateTime? purchaseStatusDate { get; set; }
public DateTime? requestDateTime { get; set; } = DateTime.Now;
public string merchantProductCode { get; set; }
public List<Coupon> coupons { get; set; }
}
public class Coupon
{
public int Id { get; set; }
public int ConfirmResponseID { get; set; }
public List<Serial> serials { get; set; }
public List<Pin> pins { get; set; }
public virtual ConfirmResponse confirmResponse { get; set; }
}
public class Serial
{
public int Id { get; set; }
public string serials { get; set; }
public int CouponID { get; set; }
public virtual Coupon coupons { get; set; }
}
My sample JSON:
"{\"referenceId\":\"0000000046\",\"paymentId\":\"MDO1037624\",\"productCode\":\"001002461285\",\"quantity\":\"1\",\"currency\":\"TL\",\"unitPrice\":\"46,47\",\"totalPrice\":\"46,47\",\"merchantProductCode\":\"\",\"purchaseStatusCode\":\"00\",\"purchaseStatusDate\":\"2019-03-17T20:58:48Z\",\"coupons\":[{\"serials\":[\"c57a55b5-b2d4-46e7-86e0-cc13726ca8a7\"],\"pins\":[\"T6VC-XC6X-3H6JS-NVWL-93PCa\"]}],\"version\":\"V1\",\"signature\":\"2f961c7dbc32c3bc128b6e69d19e8e1a\",\"applicationCode\":\"52e7cf966b724749a7c4efadc3727ed7\"}"
How can I fix this problem? I would like to insert this JSON into my database tables. I am using EF 6.
edit:
This model structure solved my problem. Now I can insert serials and pins into database.
public class ConfirmResponse
{
public int Id { get; set; }
public string referenceId { get; set; }
public string version { get; set; }
public string signature { get; set; }
public string paymentID { get; set; }
public string productCode { get; set; }
public string currency { get; set; }
public string ApplicationCode { get; set; }
public double unitPrice { get; set; }
public double totalPrice { get; set; }
public string purchaseStatusCode { get; set; }
public DateTime? purchaseStatusDate { get; set; }
public DateTime? requestDateTime { get; set; } = DateTime.Now;
public string merchantProductCode { get; set; }
public List<Coupon> coupons { get; set; }
}
public class Coupon
{
public int Id { get; set; }
public int ConfirmResponseID { get; set; }
public List<string> serials { get; set; }
public List<string> pins { get; set; }
public virtual ConfirmResponse confirmResponse { get; set; }
public List<string> StringsSerial
{
get { return serials; }
set { serials = value; }
}
public List<string> StringsPin
{
get { return pins; }
set { pins = value; }
}
[Required]
public string Serial
{
get { return String.Join(",", serials); }
set { serials = value.Split(',').ToList(); }
}
[Required]
public string Pin
{
get { return String.Join(",", pins); }
set { pins = value.Split(',').ToList(); }
}
}
Thanks in advance.
you're json is wrong
take a look into the coupons array, you initialize the serials array with an string/guid and not with a model of serial
it should be
"coupons": [{
{
"serials": [{
"serials": "c57a55b5-b2d4-46e7-86e0-cc13726ca8a7"
}
],
}
}
]...
I guess for Pins the same

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

Entity Framework not binding entity

I have the following db structure:
I am using EF6 to create the entities from database and have the following classes created by EF6:
public partial class Mechanic
{
public Mechanic()
{
this.MechanicAddresses = new HashSet<MechanicAddress>();
this.MechanicServices = new HashSet<MechanicService>();
}
public string ID { get; set; }
public string Email { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public Nullable<System.DateTime> LockoutEndDateUtc { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public string UserName { get; set; }
public string CompanyName { get; set; }
public string ContactName { get; set; }
public string MobileNumber { get; set; }
public Nullable<bool> IsMobile { get; set; }
public string Url { get; set; }
public string FaceBookUrl { get; set; }
public string TwitterUrl { get; set; }
public string Description { get; set; }
public string Discriminator { get; set; }
public bool IsEnabled { get; set; }
public bool IsAuthorised { get; set; }
public string Logo { get; set; }
public System.DateTime CreationTimestamp { get; set; }
public virtual ICollection<MechanicAddress> MechanicAddresses { get; set; }
public virtual ICollection<MechanicService> MechanicServices { get; set; }
}
public partial class MechanicAddress
{
public int ID { get; set; }
public string MechanicId { get; set; }
public string AddressLine1 { get; set; }
public string AddressLine2 { get; set; }
public string AddressLine3 { get; set; }
public string District { get; set; }
public string Region { get; set; }
public string PostalCode { get; set; }
public int CountryId { get; set; }
public System.DateTime CreationTimestamp { get; set; }
public bool IsPrimary { get; set; }
public Nullable<double> Latitude { get; set; }
public Nullable<double> Longitude { get; set; }
public System.Data.Entity.Spatial.DbGeography Location { get; set; }
public virtual Country Country { get; set; }
public virtual Mechanic Mechanic { get; set; }
}
public partial class MechanicService
{
public int ID { get; set; }
public string MechanicId { get; set; }
public string Service { get; set; }
public virtual Mechanic Mechanic { get; set; }
}
The data is correct so i expect to get data in all entities.
When i run the following linq query in my DAL:
Mechanic mech = context.Mechanics.Where(a => a.ID == id).Include(a => a.MechanicAddresses).Include(a => a.MechanicServices).FirstOrDefault();
It returns the mechanic and mechanicAddresses but mechanicServices is always empty (count == 0).
When i run the same query in LinqPad I get all entities filled as expected.
I have removed the edmx and re-created it but still get the same issue.
Please check if "MultipleActiveResultSets" is set to true and LazyLoadingEnabled is enabled in connection string. It may help.
And what about your OnModelCreating?
protected override void OnModelCreating(DbModelBuilder modelBuilder)
It's not necessary to use Include if you have LazyLoading (virtual). And If it works fine in LinqPad try to do migration into empty DB (just test). And then try to get data from test DB.
The only way i was able to resolve this was to:
delete the EDMX
script the create for the mechanicsServices table
script the data
drop the mechanicsServices table
run the create table script from above
run the insert data script
regenerate the EDMX
This now works, WTF! Can't explain it.
I know it's always best to understand what went wrong but this one beat me.
I had same problem.
If you using git, please check .edmx file old version. SSDL content may be missing.

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!

Resources