How to deserialize multiple objects in Xamarin Forms? [duplicate] - json

This question already has answers here:
How to Deserialize JSON data? C#
(5 answers)
Closed 3 years ago.
I have two different class using that I am sending json response through API to another application, in short I am getting following json response :
{
"lmob_Forms":[
{
"Fields":"Certificate Name",
"Validation":"R",
"TabIndex":"1",
"FieldType":"DropdownList",
"DateFormate":"",
"Details":null
},
],
"drop_Salutation":[
{
"id":1,
"idvalue":"Kumari"
},
{
"id":2,
"idvalue":"Mrs"
},
{
"id":3,
"idvalue":"Ms"
}
]
}
I have searched regarding the same but not able to solve this problem, Need help, Thanks In Advance :)

First of all create a model of your json object.
public class LmobForm
{
public string Fields { get; set; }
public string Validation { get; set; }
public string TabIndex { get; set; }
public string FieldType { get; set; }
public string DateFormate { get; set; }
public object Details { get; set; }
}
public class DropSalutation
{
public int id { get; set; }
public string idvalue { get; set; }
}
public class RootObject
{
public List<LmobForm> lmob_Forms { get; set; }
public List<DropSalutation> drop_Salutation { get; set; }
}
Now, simply use Newtonsoft.Json to deserialize your JSON object as:
var myObj = JsonConvert.DeserializeObject<RootObject>(jsonString);

using json2csharp
public class LmobForm
{
public string Fields { get; set; }
public string Validation { get; set; }
public string TabIndex { get; set; }
public string FieldType { get; set; }
public string DateFormate { get; set; }
public object Details { get; set; }
}
public class DropSalutation
{
public int id { get; set; }
public string idvalue { get; set; }
}
public class RootObject
{
public List<LmobForm> lmob_Forms { get; set; }
public List<DropSalutation> drop_Salutation { get; set; }
}

Related

Trying to check a json file for the correct parameters using JsonConvert.DeserisalizeObject<t>

I'm using the ACE code editor to gather Json and send it to my application. Once the Json hits the application, I need to make sure there are certain key's inside the json so I am using JsonConvert.DeserisalizeObject<t> to do this. Here's how:
public void SubmitReport(string JsonStringSend)
{
try
{
ReportItem RptItem = JsonConvert.DeserializeObject<ReportItem>(JsonStringSend);
}
catch(err)
{
return View(err);
}
}
and:
public class ReportItem
{
public Guid ReportID;
public bool RequiresFilter;
public string MimeType { get; set; }
public string ExternalID { get; set; }
public DateTime CreatedBy { get; set; }
public string ExecutionScript { get; set; }
public string ExecutionParameter { get; set; }
public string ExecutionOrderBy { get; set; }
public List<DynamicFilter> DynamicFilters { get; set; }
public bool RequiresOrgID { get; set; }
public QueryFilter ReportFilter { get; set; }
public QueryRule ReportRules { get; set; }
public List<QueryColumn> Columns { get; set; }
}
But for some reason, it bounces right over the catch even when I make sure some of the key's are incorrect. Am I not understanding the correct usage JsonConvert.DeserisalizeObject<t>? Or, is there a better way to be doing this check?
By default, the deserializer "tries it's best" to deserialize the object. But JSon.NET supports validation, the "straightforward" way is probably JSon Schema: http://www.newtonsoft.com/jsonschema.
Simple case can be handled with JSon.NET directly:
public class ReportItem
{
[JsonProperty(Required = Required.Always)]
public bool RequiresFilter;
[JsonProperty(Required = Required.Always)]
public string MimeType { get; set; }
public DateTime CreatedBy { get; set; }
public string ExecutionScript { get; set; }
public string ExecutionParameter { get; set; }
public string ExecutionOrderBy { get; set; }
public bool RequiresOrgID { get; set; }
}

Raw JSON for Key:Value

I have been looking for ages and found some similar questions but no answers which fixed my issue.
I have recently developed a Web API project with seperate server side and client side code. I am wanting to do some testing through apiary, mainly for posting data. This requires me to have a "sample" of the posted JSON. However i cannot seem to get a working sample (I am using Postman to test the JSON).
I am sending a ViewModel:
public class ExampleViewModel
{
public ExampleModel exampleModel { get; set; }
public String[] strings { get; set; }
}
With the model:
public class ExampleModel
{
public long ID { get; set; }
public string User { get; set; }
public string Title { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public bool Recieved { get; set; }
public bool CompleteRemotly { get; set; }
public bool CompleteInField { get; set; }
public string Email { get; set; }
public Nullable<DateTime> RecievedDate { get; set; }
public Nullable<DateTime> ScheduledFor { get; set; }
public Nullable<DateTime> CompleteOn { get; set; }
public string Priority { get; set; }
public string DiagnosticReports { get; set; }
public string CReference { get; set; }
public string JReference { get; set; }
}
The format the POST is expecting is:
Key: "evm",
Value: {APIProject.ViewModels.ExampleViewModel}
And:
APIProject.ViewModels.ExampleViewModel:
{
strings = [""],
exampleModel = {ExampleModel}
}
My latest attempt is:
{
"evm":{
"ExampleViewModel":{
"exampleModel":{
"ID":0,
"User":"Harrison",
"Title":"Other",
"Type":"Other",
"Description":"ygfvgufuf",
"Recieved":true,
"CompleteRemotly":false,
"CompleteInField":false,
"Email":null,
"RecievedDate":"\/Date(1458133155546)\/",
"ScheduledFor":null,
"CompleteOn":null,
"Priority":"Low",
"DiagnosticReports":null,
"CPA_Reference":null,
"Jira_Reference":null,
"strings":[]
},
"strings":[""]
}
}
}
Which returns:
Key: "evm",
Value: {APIProject.ViewModels.ExampleViewModel}
And:
APIProject.ViewModels.ExampleViewModel:
{
strings = null,
exampleModel = null
}
So i got this to work by sending the following JSON, I guess i was over complicating the situation.
{
"requestManagements":{
"RequestID":0,
"User":"Harrison",
"RequestTitle":"Other",
"RequestType":"Other",
"RequestDescription":"ygfvgufuf",
"RequestRecieved":true,
"RequestCompleteRemotly":false,
"RequestCompleteInField":false,
"Email":null,
"RequestRecievedDate":"\/Date(1458133155546)\/",
"ScheduledFor":null,
"CompleteOn":null,
"Priority":"Low",
"DiagnosticReports":null,
"CPA_Reference":null,
"Jira_Reference":null,
"RequestManagerImages":[]
},
"images":[""]
}

JSON to a JSON array Cannot deserialize the current JSON object

I'm using Json.Net to DeserializeObject Json data into object/collection (list)
I'm not sure what I'm doing wrong and I have tried this:
List<LanguageObject> lang = JsonConvert.DeserializeObject<List<LanguageObject>>(jsonData);
and tried this:
LanguageObject.Results lang = JsonConvert.DeserializeObject<LanguageObject.Results>(jsonData);
I'm getting this error:
Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[LanguageObject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'meta', line 1, position 8.
here my Json:
{"meta":
{
"status":200,
"message":[],
"resultSet":
{"id":"05"},
"pagination":
{
"count":2,
"pageNum":1,
"pageSize":2,
"totalPages":1,
"sort":"ordinal",
"order":"Asc",
"currentUri":null,
"nextUri":null
}
},
"results":
{
"id":0,
"name":
"Language",
"DName":null,
"qvalue":"language",
"language":null,
"mUsageCount":null,
"Ordinal":0,
"items":
[
{
"id":0,
"name":"English",
"DName":"English",
"qvalue":null,
"language":null,
"mUsageCount":null,
"Ordinal":0,
"items":[]
},
{
"id":0,
"name":"Spanish",
"DName":"Spanish;",
"qvalue":null,
"language":null,
"mUsageCount":null,
"Ordinal":0,"
items":[]
}
]
}}
LanguageObject.cs
Public class LanguageObject
{
public class ResultSet
{
public string id { get; set; }
}
public class Pagination
{
public int count { get; set; }
public int pageNum { get; set; }
public int pageSize { get; set; }
public int totalPages { get; set; }
public string sort { get; set; }
public string order { get; set; }
public object currentUri { get; set; }
public object nextUri { get; set; }
}
public class Meta
{
public int status { get; set; }
public List<object> message { get; set; }
public ResultSet resultSet { get; set; }
public Pagination pagination { get; set; }
}
public class Item
{
public int id { get; set; }
public string name { get; set; }
public string DName { get; set; }
public object qvalue { get; set; }
public object language { get; set; }
public object mUsageCount { get; set; }
public int Ordinal { get; set; }
public List<object> items { get; set; }
public List<object> __invalid_name__
items { get; set; }
}
public class Results
{
public int id { get; set; }
public string name { get; set; }
public object DName { get; set; }
public string qvalue { get; set; }
public object language { get; set; }
public object mUsageCount { get; set; }
public int Ordinal { get; set; }
public List<Item> items { get; set; }
}
public class RootObject
{
public Meta meta { get; set; }
public Results results { get; set; }
}
}
I don't see a LanguageObject class defined in your question. I do see a RootObject class, however. From what you have posted, you need to deserialize like this:
RootObject root = JsonConvert.DeserializeObject<RootObject>(jsonData);
Then you can get the Results from the RootObject:
Results lang = root.Results;

How can I deserialization JSON in Windows Phone?

The first JSON is look like this
The second JSON is look like this
How can I deserialize them? I have been follow this example but it's not working.
Here's my code.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
var w = new WebClient();
Observable
.FromEvent<DownloadStringCompletedEventArgs>(w, "DownloadStringCompleted")
.Subscribe(r =>
{
var deserialized =
JsonConvert.DeserializeObject<List<Place>>(r.EventArgs.Result);
PlaceList.ItemsSource = deserialized;
});
w.DownloadStringAsync(
new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place"));
//For 2nd JSON
//w.DownloadStringAsync(
//new Uri("http://mobiilivantaa.lightscreenmedia.com/api/place/243"));
}
These are classes for 1st JSON.
public class Place
{
public string id { get; set; }
public string title { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string www { get; set; }
}
public class RootObjectJSON1
{
public List<Place> Places { get; set; }
}
These are classes for JSON2
public class Address
{
public string street { get; set; }
public string postal_code { get; set; }
public string post_office { get; set; }
}
public class Image
{
public string id { get; set; }
public string filename { get; set; }
public string path { get; set; }
}
public class RootObjectJSON2
{
public string id { get; set; }
public string title { get; set; }
public string description { get; set; }
public string latitude { get; set; }
public string longitude { get; set; }
public string www { get; set; }
public string phone { get; set; }
public string email { get; set; }
public string contact_person { get; set; }
public Address address { get; set; }
public List<Image> images { get; set; }
}
it looks that you should be deserializing object RootObjectJSON1 or RootObjectJSON2, e.g.:
var deserialized = JsonConvert.DeserializeObject<RootObjectJSON1>(r.EventArgs.Result);
Also it seems that collection Places should be with lowercase p at beginning or you need to tell Json.NET that this property should be deserialized with different name, e.g.:
[JsonProperty(PropertyName="places")]
public List<Place> Places { get; set; }
Generally I tend to use arrays for deserialization (from my experience works better) so I'll suggest to rewrite it to this:
public class RootObjectJSON1
{
public Place[] places { get; set; }
}
There is very good tool named json2csharp available at http://json2csharp.com/ - just put sample of JSON there and it will spit out classes in C# (doesn't detect DateTime so you might need to change that).

Having trouble finding the right JSON request

I will appologise in advance if I am being really stupid here, but I cant find the right syntax to extract some data from a JSON return. The following is the returned JSON data:
{
"version":"1.0",
"encoding":"UTF-8",
"feed":{
"xmlns":"http://www.w3.org/2005/Atom",
"xmlns$openSearch":"http://a9.com/-/spec/opensearchrss/1.0/",
"xmlns$gsx":"http://schemas.google.com/spreadsheets/2006/extended",
"id":{
"$t":"https://spreadsheets.google.com/feeds/list/0AhySzEddwIC1dEN6bnNQYkRlVE50RlBRLUQ5YlZhNUE/1/public/basic"
},
"updated":{
"$t":"2012-12-03T10:33:13.778Z"
},
"category":[
{
"scheme":"http://schemas.google.com/spreadsheets/2006",
"term":"http://schemas.google.com/spreadsheets/2006#list"
}
],
"title":{
"type":"text",
"$t":"Sheet1"
},
"link":[
{
"rel":"alternate",
"type":"text/html",
"href":"https://spreadsheets.google.com/pub?key\u003d0AhySzEddwIC1dEN6bnNQYkRlVE50RlBRLUQ5YlZhNUE"
},
{
"rel":"http://schemas.google.com/g/2005#feed",
"type":"application/atom+xml",
"href":"https://spreadsheets.google.com/feeds/list/0AhySzEddwIC1dEN6bnNQYkRlVE50RlBRLUQ5YlZhNUE/1/public/basic"
},
{
"rel":"self",
"type":"application/atom+xml",
"href":"https://spreadsheets.google.com/feeds/list/0AhySzEddwIC1dEN6bnNQYkRlVE50RlBRLUQ5YlZhNUE/1/public/basic?alt\u003djson"
}
],
"author":[
{
"name":{
"$t":"rourkie"
},
"email":{
"$t":"rourkie#gmail.com"
}
}
],
"openSearch$totalResults":{
"$t":"1"
},
"openSearch$startIndex":{
"$t":"1"
},
"entry":[
{
"id":{
"$t":"https://spreadsheets.google.com/feeds/list/0AhySzEddwIC1dEN6bnNQYkRlVE50RlBRLUQ5YlZhNUE/1/public/basic/cn6ca"
},
"updated":{
"$t":"2012-12-03T10:33:13.778Z"
},
"category":[
{
"scheme":"http://schemas.google.com/spreadsheets/2006",
"term":"http://schemas.google.com/spreadsheets/2006#list"
}
],
"title":{
"type":"text",
"$t":"5872.64"
},
"content":{
"type":"text",
"$t":"change: 3.6"
},
"link":[
{
"rel":"self",
"type":"application/atom+xml",
"href":"https://spreadsheets.google.com/feeds/list/0AhySzEddwIC1dEN6bnNQYkRlVE50RlBRLUQ5YlZhNUE/1/public/basic/cn6ca"
}
]
}
]
}
}
I am trying to extract the "change" figure, with the following:
feed.entry[4].content.$t
but it just keeps returning an error.
Can anyone shed some light on what I am doing wrong??
Thanks
JSONLint - http://jsonlint.com/ - is pretty handy for this.
The JSON you posted only has one object in the entry array (unless you just posted it as an example)...so it would be:
feed.entry[0].content.$t
Using json2csharp.com (http://json2csharp.com/) You can paste in json and it will give you a class matching the json allowing you to easily parse it. Check How can I parse JSON with C#? on how to use JsonConvert. I believe you can find it in nuget packages. Keep in mind the class I have pasted below will not work directly, because of the naming of some of the fields in the json. You may have to rename them manually and map them.
public class Id
{
public string __invalid_name__$t { get; set; }
}
public class Updated
{
public string __invalid_name__$t { get; set; }
}
public class Category
{
public string scheme { get; set; }
public string term { get; set; }
}
public class Title
{
public string type { get; set; }
public string __invalid_name__$t { get; set; }
}
public class Link
{
public string rel { get; set; }
public string type { get; set; }
public string href { get; set; }
}
public class Name
{
public string __invalid_name__$t { get; set; }
}
public class Email
{
public string __invalid_name__$t { get; set; }
}
public class Author
{
public Name name { get; set; }
public Email email { get; set; }
}
public class OpenSearchTotalResults
{
public string __invalid_name__$t { get; set; }
}
public class OpenSearchStartIndex
{
public string __invalid_name__$t { get; set; }
}
public class Id2
{
public string __invalid_name__$t { get; set; }
}
public class Updated2
{
public string __invalid_name__$t { get; set; }
}
public class Category2
{
public string scheme { get; set; }
public string term { get; set; }
}
public class Title2
{
public string type { get; set; }
public string __invalid_name__$t { get; set; }
}
public class Content
{
public string type { get; set; }
public string __invalid_name__$t { get; set; }
}
public class Link2
{
public string rel { get; set; }
public string type { get; set; }
public string href { get; set; }
}
public class Entry
{
public Id2 id { get; set; }
public Updated2 updated { get; set; }
public List<Category2> category { get; set; }
public Title2 title { get; set; }
public Content content { get; set; }
public List<Link2> link { get; set; }
}
public class Feed
{
public string xmlns { get; set; }
public string __invalid_name__xmlns$openSearch { get; set; }
public string __invalid_name__xmlns$gsx { get; set; }
public Id id { get; set; }
public Updated updated { get; set; }
public List<Category> category { get; set; }
public Title title { get; set; }
public List<Link> link { get; set; }
public List<Author> author { get; set; }
public OpenSearchTotalResults __invalid_name__openSearch$totalResults { get; set; }
public OpenSearchStartIndex __invalid_name__openSearch$startIndex { get; set; }
public List<Entry> entry { get; set; }
}
public class RootObject
{
public string version { get; set; }
public string encoding { get; set; }
public Feed feed { get; set; }
}