I am trying to deserialize a json object into c# object and list the Itinerary items.
Here is my json object:
{
"data": {
"Itineraries": [
{
"isDomestic": false,
"departureAirport": "IKA",
"arrivalAirport": "IST"
},
{
"isDomestic": false,
"departureAirport": "IST",
"arrivalAirport": "LAX"
}
]
}
}
here is my c# classes that I use
public class Data
{
public List<itineraries> itineraries { get; set; } = new List<itineraries>();
}
public class itineraries
{
public bool isDomestic { get; set; }
public string departureAirport { get; set; }
public string arrivalAirport { get; set; }
}
here is the code that I use to deserialize
Data availableData= JsonSerializer.Deserialize<Data>(json);
foreach (var item in availableData.itineraries){
Console.WriteLine($"departureAirport:{item.departureAirport}");
}
But I could not list the itineraries.
try this classes
public class Itinerary
{
public bool isDomestic { get; set; }
public string departureAirport { get; set; }
public string arrivalAirport { get; set; }
}
public class Data
{
public List<Itinerary> Itineraries { get; set; }
}
public class Root
{
public Data data { get; set; }
}
and code
var availableData= JsonSerializer.Deserialize<Root>(json);
foreach (var item in availableData.data.Itineraries)
{
Console.WriteLine($"departureAirport:{item.departureAirport}");
}
first, you have to install Newtonsoft.Json from NuGet Manager
then use these classes instead of yours
public class Itinerary
{
public bool isDomestic { get; set; }
public string departureAirport { get; set; }
public string arrivalAirport { get; set; }
}
public class Data
{
public List<Itinerary> Itineraries { get; set; }
}
public class Root
{
public Data data { get; set; }
}
the convert code is
var root = JsonConvert.DeserializeObject<Root>(json);
Related
This question already has an answer here:
Deserialize Nested JSON
(1 answer)
Closed 1 year ago.
I need to deserialize some JSON with this format:
{
"message": {
"header": {
"status_code": 200,
"execute_time": 0.29062294960022,
"available": 10000
},
"body": {
"track_list": [
{
"track": {
"track_id": 45085706,
"track_name": "Love Overdose (Deboa & Hannah Holland Remix)",
"primary_genres": {
"music_genre_list": [
{
"music_genre": {
"music_genre_name": "Dance"
}
}
]
}
}
}
]
}
}
}
I have these classes which I got from online generator, so I assume they are ok.
public class Header
{
public int status_code { get; set; }
public double execute_time { get; set; }
public int available { get; set; }
}
public class MusicGenre
{
public int music_genre_id { get; set; }
public int music_genre_parent_id { get; set; }
public string music_genre_name { get; set; }
public string music_genre_name_extended { get; set; }
public string music_genre_vanity { get; set; }
}
public class MusicGenreList
{
public MusicGenre music_genre { get; set; }
}
public class PrimaryGenres
{
public List<MusicGenreList> music_genre_list { get; set; }
}
public class Track
{
public int track_id { get; set; }
public string track_name { get; set; }
public List<object> track_name_translation_list { get; set; }
public int track_rating { get; set; }
public int commontrack_id { get; set; }
public int instrumental { get; set; }
public int #explicit { get; set; }
public int has_lyrics { get; set; }
public int has_subtitles { get; set; }
public int has_richsync { get; set; }
public int num_favourite { get; set; }
public int album_id { get; set; }
public string album_name { get; set; }
public int artist_id { get; set; }
public string artist_name { get; set; }
public string track_share_url { get; set; }
public string track_edit_url { get; set; }
public int restricted { get; set; }
public DateTime updated_time { get; set; }
public PrimaryGenres primary_genres { get; set; }
}
public class TrackList
{
public Track track { get; set; }
}
public class Body
{
public List<TrackList> TrackList { get; set; }
}
public class Message
{
public Header header { get; set; }
public Body body { get; set; }
}
public class Root
{
public Message message { get; set; }
}
I tried to deserialize the JSON with this code:
using (StreamReader r = new StreamReader(#"c:\users\xxxx\desktop\1.json"))
{
string json = r.ReadToEnd();
var tracks = JsonConvert.DeserializeObject<Track>(json);
}
but I got nothing. I'm new to this; made it with simpler JSON, but I can't figure out how to do it with this code. I want to print a list with just the song names.
If anyone can help me I would appreciate it!
There are a couple of problems here:
In your Body class, the TrackList property does not match the JSON. The corresponding property in the JSON is called track_list. The class properties must either exactly match the JSON (ignoring case) or else you need to use a [JsonProperty] attribute on the property to indicate what the JSON name will be. For example:
public class Body
{
[JsonProperty("track_list")]
public List<TrackList> TrackList { get; set; }
}
You are attempting to deserialize into the Track class, but you should be deserializing to Root since that represents the root of the JSON.
var root = JsonConvert.DeserializeObject<Root>(json);
Once you have deserialized to Root you can "drill down" to print out the tracks.
foreach (var item in root.message.body.TrackList)
{
Console.WriteLine(item.track.track_name);
}
Fiddle: https://dotnetfiddle.net/JnljGU
i have a json response object but i unable to create a class structure for following json response object .
{
"PWSESSIONRS": [
{
"PWPROCESSRS": {
"PWHEADER": {
"APP_ID": "HSA",
"ORG_ID": "HSA",
"OUT_PROCESS_ID": "weconnect_validate",
"IN_PROCESS_ID": "weconnect_validate",
"LOGIN_ID": "TEST10800"
},
"PWDATA": {
"weconnect_validate": {
"Row": [
{
"success": "1"
}
]
}
}
}
}
]
}
Please suggest me some class structure. I have created following class structure but Json.Convert unable to deserialize it.
public class LoginSuccess
{
public List<PwProcessorSuccess> PWSESSIONRS { get; set; }
}
public class RowSuccess
{
public string success { get; set; }
}
public class WeconnectValidateSuccess
{
public List<RowSuccess> Row { get; set; }
}
public class PwDataSuccess
{
public WeconnectValidateSuccess weconnect_validate { get; set; }
}
public class PwHeaderSucess
{
public string LOGIN_ID { get; set; }
public string ORG_ID { get; set; }
public string APP_ID { get; set; }
public string IN_PROCESS_ID { get; set; }
public string OUT_PROCESS_ID { get; set; }
}
public class PwProcessorSuccess
{
public PwHeaderSucess PWHEADER { get; set; }
public PwDataSuccess PWDATA { get; set; }
}
Please help.
I made the classes for you from the beginning so that following code to help you a lot and your problem will be solved instantly.
You can use the below code:
public class MainKeepClass
{
public PWSESSIONR[] PWSESSIONRS { get; set; }
}
public class PWSESSIONR
{
public PWPROCESSRS PWPROCESSRS { get; set; }
}
public class PWPROCESSRS
{
public PWHEADER PWHEADER { get; set; }
public PWDATA PWDATA { get; set; }
}
public class PWHEADER
{
public string APP_ID { get; set; }
public string ORG_ID { get; set; }
public string OUT_PROCESS_ID { get; set; }
public string IN_PROCESS_ID { get; set; }
public string LOGIN_ID { get; set; }
}
public class PWDATA
{
public Weconnect_Validate weconnect_validate { get; set; }
}
public class Weconnect_Validate
{
public Row[] Row { get; set; }
}
public class Row
{
public string success { get; set; }
}
This question already has answers here:
Deserialize JSON with dot in property name
(2 answers)
Closed 2 years ago.
I have a JSON response like below:
{
"sitePropertiesMap":
{
"site.web.url.protocol":
{
"sitePropertyId": 2497,
"siteId": 66,
"key": "site.web.url.protocol",
"value": "https",
"type": null,
"globalAdminOnly": "disabled",
"hideDefaultValue": "disabled"
}
}
}
How can I access the "sitePropertyId" value from this? I tried to create a modal class like below:
public class sitePropertiesMap
{
public class site.web.url.protocol
{
public string sitePropertyId { get; set; }
}
}
But getting an error because the class name having a dot operator(.)
Error Screenshot:
In this case, how can I parse the JSON value?
You can use the JsonProperty attribute of JSON.NET
public class Rootobject
{
public Sitepropertiesmap sitePropertiesMap { get; set; }
}
public class Sitepropertiesmap
{
[JsonProperty(PropertyName = "site.web.url.protocol")]
public SiteWebUrlProtocol siteweburlprotocol { get; set; }
}
public class SiteWebUrlProtocol
{
public int sitePropertyId { get; set; }
public int siteId { get; set; }
public string key { get; set; }
public string value { get; set; }
public object type { get; set; }
public string globalAdminOnly { get; set; }
public string hideDefaultValue { get; set; }
}
And then deserialize like this:
var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Rootobject>(json);
You need to use using Newtonsoft.Json; to use this.
You can use a dictionary
public class RootObject
{
public Dictionary<string,SiteProperties> SitePropertiesMap { get; set; }
}
public class SiteProperties
{
public int SitePropertyId { get; set; }
public int SiteId { get; set; }
public string Key { get; set; }
public string Value { get; set; }
public string GlobalAdminOnly { get; set; }
public string HideDefaultValue { get; set; }
}
and access the value like
obj.SitePropertiesMap["site.web.url.protocol"].SitePropertyId
.net fiddle example
One approach is to use Newtonsoft's PropertyName attribute and remove the dots inside the property's name of your model class.
https://dotnetfiddle.net/uFnHEK
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
var json = "{\"sitePropertiesMap\": { \"site.web.url.protocol\": { \"sitePropertyId\": 2497, \"siteId\": 66, \"key\": \"site.web.url.protocol\", \"value\": \"https\", \"type\": null, \"globalAdminOnly\": \"disabled\", \"hideDefaultValue\": \"disabled\" } } }";
var obj = JsonConvert.DeserializeObject<RootObject>(json);
Console.WriteLine(obj.sitePropertiesMap.SiteWebUrlProtocol.sitePropertyId);
}
}
public class SiteWebUrlProtocol
{
public int sitePropertyId { get; set; }
public int siteId { get; set; }
public string key { get; set; }
public string value { get; set; }
public object type { get; set; }
public string globalAdminOnly { get; set; }
public string hideDefaultValue { get; set; }
}
public class SitePropertiesMap
{
[JsonProperty(PropertyName = "site.web.url.protocol")]
public SiteWebUrlProtocol SiteWebUrlProtocol { get; set; }
}
public class RootObject
{
public SitePropertiesMap sitePropertiesMap { get; set; }
}
I get the following response from a webservice:
{
"data":{
"foo.hugo.info": {
"path": "logon.cgi",
"minVersion": 1,
"maxVersion": 2
},
"foo.Fritz.Task": {
"path": "Fritz/process.cgi",
"minVersion": 1,
"maxVersion": 1
}
},
"success": true
}
How must the json-object look like to deserialize this?
Or is there another way to get the values of the properties?
With the JSON.NET library it's pretty trivial:
public class Root
{
public Dictionary<string, Data> Data { get; set; }
public bool Success { get; set; }
}
public class Data
{
public string Path { get; set; }
public int MinVersion { get; set; }
public int MaxVersion { get; set; }
}
and then:
string json =
#"{
""data"":{
""foo.hugo.info"": {
""path"": ""logon.cgi"",
""minVersion"": 1,
""maxVersion"": 2
},
""foo.Fritz.Task"": {
""path"": ""Fritz/process.cgi"",
""minVersion"": 1,
""maxVersion"": 1
}
},
""success"": true
}";
Root root = JsonConvert.DeserializeObject<Root>(json);
In this example I have used a Dictionary<string, Data> object to model the 2 complex keys (foo.hugo.info and foo.Fritz.Task) because they contain names that cannot be used in a .NET member.
If you're using VS2012 or above you can do the following:
Edit > Paste Special > Paste JSON As Classes
With your example, this results in:
public class Rootobject
{
public Data data { get; set; }
public bool success { get; set; }
}
public class Data
{
public FooHugoInfo foohugoinfo { get; set; }
public FooFritzTask fooFritzTask { get; set; }
}
public class FooHugoInfo
{
public string path { get; set; }
public int minVersion { get; set; }
public int maxVersion { get; set; }
}
public class FooFritzTask
{
public string path { get; set; }
public int minVersion { get; set; }
public int maxVersion { get; set; }
}
Check out this site: http://json2csharp.com/
Paste in the json string and it will generate classes for you. I usually use this in hand with JSON.NET to deserialize an instance of the Root Object.
You can use DataContractJsonSerializer
[DataContract]
public class DetailedData
{
[DataMember(Name="path")]
public string Path { get; set; }
[DataMember(Name = "minVersion")]
public int MinVersion { get; set; }
[DataMember(Name = "maxVersion")]
public int MaxVersion { get; set; }
}
[DataContract]
public class Data
{
[DataMember(Name = "foo.hugo.info")]
public DetailedData Info { get; set; }
[DataMember(Name = "foo.Fritz.Task")]
public DetailedData Task { get; set; }
}
[DataContract]
public class RootObject
{
[DataMember(Name = "data")]
public Data Data { get; set; }
[DataMember(Name = "success")]
public bool Success { get; set; }
}
static void Main(string[] args)
{
string json = "...";
DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(RootObject));
RootObject obj = (RootObject)js.ReadObject(new MemoryStream(Encoding.Unicode.GetBytes(json)));
Console.WriteLine(obj.Data.Task.MaxVersion);
}
Edit: same class for Info and Task
I have a JSON object like the following
{
"data": [
{
"id": "18128270850211_49239570772655",
"from": {
"name": "Someone Unimportant",
"id": "57583427"
}
/* more stuff */
}
]
}
I want to parse it using JSON.NET,
FacebookResponse<FacebookPost> response = JsonConvert.DeserializeObject<FacebookResponse<FacebookPost>>(json);
internal class FacebookResponse<T> where T : class
{
public IList<T> Data { get; set; }
public FacebookResponsePaging Paging { get; set; }
}
public class FacebookPost
{
public string Id { get; set; }
[JsonProperty("to.data.id")]
public string FeedId { get; set; }
[JsonProperty("from.id")]
public string UserId { get; set; }
[JsonProperty("created_time")]
public DateTime CreatedTime { get; set; }
[JsonProperty("updated_time")]
public DateTime UpdatedTime { get; set; }
public string Type { get; set; } // TODO: Type enum??
public string Message { get; set; }
public string Link { get; set; }
public string Name { get; set; }
public string Caption { get; set; }
public string Description { get; set; }
}
Everything comes through except for the FeedId and the UserId properties. How should I be mapping these?
public class From
{
public string name { get; set; }
public string id { get; set; }
}
public class Datum
{
public string id { get; set; }
public From from { get; set; }
}
public class FacebookPost
{
public List<Datum> data { get; set; }
}
internal class FacebookResponse<T> where T : class
{
public IList<T> Data { get; set; }
public FacebookResponsePaging Paging { get; set; }
}
FacebookResponse<FacebookPost> response = JsonConvert.DeserializeObject<FacebookResponse<FacebookPost>>(json);
Try below code :)
Use this site to get the object for .net
Then you can use JSON.Net to deserialize: ex.JsonConvert.DeserializeObject(input) iirc