How to deserialize json property to class property? - c#

My JSON file
[
{
"amount":"1000000.0",
"check_number":1,
"payment_number":5,
"attachments":[
{
"id":5324,
"url":"http://www.example.com/",
"filename":"january_receipt_copy.jpg"
}
]
}
]
My Class File
public class Attachment
{
public int id { get; set; }
public string url { get; set; }
public string filename { get; set; }
}
public class AccountDetail
{
public string amount { get; set; }
public int check_number { get; set; }
public int payment_number { get; set; }
}
public class RootObject
{
public AccountDetail accountdetail{ get; set; }
public List<Attachment> attachments { get; set; }
}
Now I want to map JSON file's properties 'check_number','amount' etc
to accountdetail by using newtonsoft JSON deserialization.

You need the following two classes:
public class Attachment
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("url")]
public string Url { get; set; }
[JsonProperty("filename")]
public string Filename { get; set; }
}
public class AccountDetails
{
[JsonProperty("amount")]
public string Amount { get; set; }
[JsonProperty("check_number")]
public int CheckNumber { get; set; }
[JsonProperty("payment_number")]
public int PaymentNumber { get; set; }
[JsonProperty("attachments")]
public IList<Attachment> Attachments { get; set; }
}
By defining the above classes you can deserialize your json as below:
var accountsDetails = JsonConvert.DeserializeObject<IEnumerable<AccountDetails>>(json);

Related

Alternative to naming an c# class attribute '#' when converting files with mentioned attribute from json [duplicate]

I have a JSON request which has follwing structure:
"formats": {
"flash_embed": "http://a3.vikiassets.com/assets/vikiplayer-922746a667cfd38137a7e45df6ba1b95.swf?auto_play=true&language_codes=en&media_id=74965&partner=16&source=api_v3",
"m3u8": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965/ios.m3u8",
"res-150p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_mp4cell_150.mp4",
"res-240p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_240p.mp4",
"res-270p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_270p.mp4",
"res-360p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_360p.mp4",
"res-480p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_480p.mp4",
"res-720p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_720p.mp4"
}
}
Now res-150p, says invalid name in C# and if I give another name to it then while desiralizing I am not getting any values, that is null inside res-150p.
Edit:
[Serializable]
MoviesListRootObject is the root Object which Contains Response and then Response Contains Formats
public class MoviesListRootObject
{
public int count { get; set; }
public Pagination pagination { get; set; }
public List<Response> response { get; set; }
}
[Serializable]
public class Response
{
public int id { get; set; }
public int channel_id { get; set; }
public string title { get; set; }
public string title_language { get; set; }
public string description { get; set; }
public string description_language { get; set; }
public string created_at { get; set; }
public string uri { get; set; }
public string web_uri { get; set; }
public List<object> genres { get; set; }
public string origin_country { get; set; }
public string image { get; set; }
public Subtitles subtitles { get; set; }
public Formats formats { get; set; }
}
[Serializable]
public class Formats
{
public string flash_embed { get; set; }
public string m3u8 { get; set; }
public string __invalid_name__res150p { get; set; }
public string __invalid_name__res240p { get; set; }
public string __invalid_name__res270p { get; set; }
public string __invalid_name__res360p { get; set; }
public string __invalid_name__res480p { get; set; }
public string __invalid_name__res720p { get; set; }
public string __invalid_name__flv480p { get; set; }
public string __invalid_name__flv360p { get; set; }
public string __invalid_name__flv270p { get; set; }
public string __invalid_name__flvvp6360p { get; set; }
public string __invalid_name__flvvp6270p { get; set; }
}
You have to decorate your Formats properties with JsonProperty attributes to tell it what goes where if the name does not exactly match:
partial class Formats
{
[JsonProperty("res-150p")]
public string __invalid_name__res150p {get; set;}
}
See also Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

How should I handle Wordpress rest json in C# when json2csharp is returning an invalid name? [duplicate]

I have a JSON request which has follwing structure:
"formats": {
"flash_embed": "http://a3.vikiassets.com/assets/vikiplayer-922746a667cfd38137a7e45df6ba1b95.swf?auto_play=true&language_codes=en&media_id=74965&partner=16&source=api_v3",
"m3u8": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965/ios.m3u8",
"res-150p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_mp4cell_150.mp4",
"res-240p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_240p.mp4",
"res-270p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_270p.mp4",
"res-360p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_360p.mp4",
"res-480p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_480p.mp4",
"res-720p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_720p.mp4"
}
}
Now res-150p, says invalid name in C# and if I give another name to it then while desiralizing I am not getting any values, that is null inside res-150p.
Edit:
[Serializable]
MoviesListRootObject is the root Object which Contains Response and then Response Contains Formats
public class MoviesListRootObject
{
public int count { get; set; }
public Pagination pagination { get; set; }
public List<Response> response { get; set; }
}
[Serializable]
public class Response
{
public int id { get; set; }
public int channel_id { get; set; }
public string title { get; set; }
public string title_language { get; set; }
public string description { get; set; }
public string description_language { get; set; }
public string created_at { get; set; }
public string uri { get; set; }
public string web_uri { get; set; }
public List<object> genres { get; set; }
public string origin_country { get; set; }
public string image { get; set; }
public Subtitles subtitles { get; set; }
public Formats formats { get; set; }
}
[Serializable]
public class Formats
{
public string flash_embed { get; set; }
public string m3u8 { get; set; }
public string __invalid_name__res150p { get; set; }
public string __invalid_name__res240p { get; set; }
public string __invalid_name__res270p { get; set; }
public string __invalid_name__res360p { get; set; }
public string __invalid_name__res480p { get; set; }
public string __invalid_name__res720p { get; set; }
public string __invalid_name__flv480p { get; set; }
public string __invalid_name__flv360p { get; set; }
public string __invalid_name__flv270p { get; set; }
public string __invalid_name__flvvp6360p { get; set; }
public string __invalid_name__flvvp6270p { get; set; }
}
You have to decorate your Formats properties with JsonProperty attributes to tell it what goes where if the name does not exactly match:
partial class Formats
{
[JsonProperty("res-150p")]
public string __invalid_name__res150p {get; set;}
}
See also Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Json string deserialization C#

I have this json
and i want to deserialize it so I can get each object's value for example:
"icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpouLWzKjhzw8zFdC5K092kl5SClMj3PLXFhGpC_Pp8j-3I4IG7i1Hn_UI-Nmj3ItDGe1BoN1mCr1G4xL_vhMS8tcmcn3JhuihwsHvbzQv3309k3tBw8A",
The problem is I can make the class(es) that I need so I can deserialize the json because the json string has nested objects.
I used json2csharp to help me generate classes. After some merging and cleaning up, this is what I got:
public class InventoryItem
{
public string id { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string amount { get; set; }
public int pos { get; set; }
}
public class AppData
{
public string def_index { get; set; }
public int? is_itemset_name { get; set; }
public int? limited { get; set; }
}
public class Description
{
public string type { get; set; }
public string value { get; set; }
public string color { get; set; }
public AppData app_data { get; set; }
}
public class Action
{
public string name { get; set; }
public string link { get; set; }
}
public class Tag
{
public string internal_name { get; set; }
public string name { get; set; }
public string category { get; set; }
public string category_name { get; set; }
public string color { get; set; }
}
public class RgDescription
{
public string appid { get; set; }
public string classid { get; set; }
public string instanceid { get; set; }
public string icon_url { get; set; }
public string icon_url_large { get; set; }
public string icon_drag_url { get; set; }
public string name { get; set; }
public string market_hash_name { get; set; }
public string market_name { get; set; }
public string name_color { get; set; }
public string background_color { get; set; }
public string type { get; set; }
public int tradable { get; set; }
public int marketable { get; set; }
public int commodity { get; set; }
public string market_tradable_restriction { get; set; }
public List<Description> descriptions { get; set; }
public List<Action> actions { get; set; }
public List<Action> market_actions { get; set; }
public List<Tag> tags { get; set; }
}
public class RootObject
{
public bool success { get; set; }
public IDictionary<string, InventoryItem> rgInventory { get; set; }
public List<object> rgCurrency { get; set; }
public IDictionary<string, RgDescription> rgDescriptions { get; set; }
public bool more { get; set; }
public bool more_start { get; set; }
}
These appear to work correctly, you can deserialize and serialize with code like this:
var obj = JsonConvert.DeserializeObject<RootObject>(oldString);
Console.WriteLine(obj.rgDescriptions["310776560_302028390"].icon_url); // e.g.
var newString = JsonConvert.SerializeObject(obj,
new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
// null value handling is optional, the above makes it a little more like the source string

Generate C# object from Json string and parse Json string to generated object

I am trying to generate C# class using the JSON string from here http://json2csharp.com/ this works fine. But I can't parse the JSON to the object generated by the website.
Here is the JSON string
{
"searchParameters":{
"key":"**********",
"system":"urn:oid:.8"
},
"message":" found one Person matching your search criteria.",
"_links":{
"self":{
"href":"https://integration.rest.api.test.com/v1/person?key=123456&system=12.4.34.."
}
},
"_embedded":{
"person":[
{
"details":{
"address":[
{
"line":["5554519 testdr"],
"city":"testland",
"state":"TT",
"zip":"12345",
"period":{
"start":"2003-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"name":[
{
"use":"usual",
"family":["BC"],
"given":["TWO"],
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"gender":{
"code":"M",
"display":"Male"
},
"birthDate":"9999-02-03T00:00:00Z",
"identifier":[
{
"use":"unspecified",
"system":"urn:oid:2.19.8",
"key":"",
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"telecom":[
{
"system":"email",
"value":"test#test.com",
"use":"unspecified",
"period":{
"start":"9999-10-22T00:00:00Z",
"end":"9999-12-31T23:59:59Z"
}
}
],
"photo":[
{
"content":{
"contentType":"image/jpeg",
"language":"",
"data":"",
"size":0,
"hash":"",
"title":"My Picture"
}
}
]
},
"enrolled":true,
"enrollmentSummary":{
"dateEnrolled":"9999-02-07T21:39:11.174Z",
"enroller":"test Support"
},
"_links":{
"self":{
"href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc"
},
"unenroll":{
"href":"https://integration.rest.api.test.com/v1/person/1b018dc4-182d-4296-90cc-/unenroll"
},
"personLink":{
"href":"https://integration.rest.api.test.com/v1/person/-182d-4296-90cc-953c/personLink"
},
"personMatch":{
"href":"https://integration.rest.api.commonwellalliance.org/v1/person/-182d-4296-90cc-/personMatch?orgId="
}
}
}
]
}
}
Here is the code I use to convert to the object.
JavaScriptSerializer js = new JavaScriptSerializer();
var xx = (PersonsearchVM)js.Deserialize(jsonstr, typeof(PersonsearchVM));
Is there any other wat to generate the object and parse?
I think you have some invalid characters in your JSON string. Run it through a validator and add the necessary escape characters.
http://jsonlint.com/
You aren't casting it to the right object. Cast it to the type RootObject.
Eg
JavaScriptSerializer js = new JavaScriptSerializer();
var xx = (RootObject)js.Deserialize(jsonstr, typeof(RootObject));
The code that json 2 csharp creates is this:
public class SearchParameters
{
public string key { get; set; }
public string system { get; set; }
}
public class Self
{
public string href { get; set; }
}
public class LinKs
{
public Self self { get; set; }
}
public class Period
{
public string start { get; set; }
public string end { get; set; }
}
public class Address
{
public List<string> line { get; set; }
public string city { get; set; }
public string __invalid_name__state { get; set; }
public string zip { get; set; }
public Period period { get; set; }
}
public class PerioD2
{
public string start { get; set; }
public string end { get; set; }
}
public class Name
{
public string use { get; set; }
public List<string> family { get; set; }
public List<string> given { get; set; }
public PerioD2 __invalid_name__perio
d { get; set; }
}
public class Gender
{
public string __invalid_name__co
de { get; set; }
public string display { get; set; }
}
public class Period3
{
public string start { get; set; }
public string __invalid_name__end { get; set; }
}
public class Identifier
{
public string use
{ get; set; }
public string system { get; set; }
public string key { get; set; }
public Period3 period { get; set; }
}
public class Period4
{
public string start { get; set; }
public string end { get; set; }
}
public class Telecom
{
public string system { get; set; }
public string value { get; set; }
public string use { get; set; }
public Period4 period { get; set; }
}
public class Content
{
public string contentType { get; set; }
public string language { get; set; }
public string __invalid_name__dat
a { get; set; }
public int size { get; set; }
public string hash { get; set; }
public string title { get; set; }
}
public class Photo
{
public Content content { get; set; }
}
public class Details
{
public List<Address> address { get; set; }
public List<Name> name { get; set; }
public Gender gender { get; set; }
public string birthDate { get; set; }
public List<Identifier> identifier { get; set; }
public List<Telecom> telecom { get; set; }
public List<Photo> photo { get; set; }
}
public class EnrollmentSummary
{
public string dateEnrolled { get; set; }
public string __invalid_name__en
roller { get; set; }
}
public class Self2
{
public string href { get; set; }
}
public class UnEnroll
{
public string href { get; set; }
}
public class PersonLink
{
public string href { get; set; }
}
public class PersonMatch
{
public string href { get; set; }
}
public class Links2
{
public Self2 self { get; set; }
public UnEnroll __invalid_name__un
enroll { get; set; }
public PersonLink personLink { get; set; }
public PersonMatch personMatch { get; set; }
}
public class Person
{
public Details details { get; set; }
public bool __invalid_name__e
nrolled { get; set; }
public EnrollmentSummary enrollmentSummary { get; set; }
public Links2 _links { get; set; }
}
public class Embedded
{
public List<Person> person { get; set; }
}
public class RootObject
{
public SearchParameters searchParameters { get; set; }
public string message { get; set; }
public LinKs __invalid_name___lin
ks { get; set; }
public Embedded _embedded { get; set; }
}
The following function will convert JSON into a C# class where T is the class type.
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
obj = (T)serializer.ReadObject(ms); //
return obj;
}
}
You need a reference to the System.Runtime.Serialization.json namespace.
The function is called in the following manner;
calendarList = Deserialise<GoogleCalendarList>(calendarListString);
calendarlist being the C# class and calendarListString the string containing the JSON.

How to Deserialize an JSON object with invalid field name in it

I have a JSON request which has follwing structure:
"formats": {
"flash_embed": "http://a3.vikiassets.com/assets/vikiplayer-922746a667cfd38137a7e45df6ba1b95.swf?auto_play=true&language_codes=en&media_id=74965&partner=16&source=api_v3",
"m3u8": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965/ios.m3u8",
"res-150p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_mp4cell_150.mp4",
"res-240p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_240p.mp4",
"res-270p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_270p.mp4",
"res-360p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_360p.mp4",
"res-480p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_480p.mp4",
"res-720p": "http://wpc.354a.edgecastcdn.net/00354A/videos/encoded/74965_720p.mp4"
}
}
Now res-150p, says invalid name in C# and if I give another name to it then while desiralizing I am not getting any values, that is null inside res-150p.
Edit:
[Serializable]
MoviesListRootObject is the root Object which Contains Response and then Response Contains Formats
public class MoviesListRootObject
{
public int count { get; set; }
public Pagination pagination { get; set; }
public List<Response> response { get; set; }
}
[Serializable]
public class Response
{
public int id { get; set; }
public int channel_id { get; set; }
public string title { get; set; }
public string title_language { get; set; }
public string description { get; set; }
public string description_language { get; set; }
public string created_at { get; set; }
public string uri { get; set; }
public string web_uri { get; set; }
public List<object> genres { get; set; }
public string origin_country { get; set; }
public string image { get; set; }
public Subtitles subtitles { get; set; }
public Formats formats { get; set; }
}
[Serializable]
public class Formats
{
public string flash_embed { get; set; }
public string m3u8 { get; set; }
public string __invalid_name__res150p { get; set; }
public string __invalid_name__res240p { get; set; }
public string __invalid_name__res270p { get; set; }
public string __invalid_name__res360p { get; set; }
public string __invalid_name__res480p { get; set; }
public string __invalid_name__res720p { get; set; }
public string __invalid_name__flv480p { get; set; }
public string __invalid_name__flv360p { get; set; }
public string __invalid_name__flv270p { get; set; }
public string __invalid_name__flvvp6360p { get; set; }
public string __invalid_name__flvvp6270p { get; set; }
}
You have to decorate your Formats properties with JsonProperty attributes to tell it what goes where if the name does not exactly match:
partial class Formats
{
[JsonProperty("res-150p")]
public string __invalid_name__res150p {get; set;}
}
See also Using JsonConvert.DeserializeObject to deserialize Json to a C# POCO class

Categories