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
Related
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);
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 am new to working with JSON in C# using Newtonsoft JSON.Net and having a problem deserializing the following response. Here's the first part of it.
"response":{
"sxt_func_ack":
{"sxt_func_ack":
[
{"coNo":1,"correlation_data":"","data1":"11036990-00","errorNo":0 ...}
]
},
Here's the beginning of the class
public class response_cls : Response
{
public response_cls()
{
sxapi_oehdr = new Generic.List<sxapi_oehdr_cls>();
sxapi_oeitm = new Generic.List<sxapi_oeitm_cls>();
sxt_func_ack = new Generic.List<sxt_func_ack_cls>();
}
public Generic.List<sxt_func_ack_cls> sxt_func_ack { get; set; }
public Generic.List<sxapi_oehdr_cls> sxapi_oehdr { get; set; }
public Generic.List<sxapi_oeitm_cls> sxapi_oeitm { get; set; }
}
What do I need to do to the class to be able to deserialize this data?
Thanks.
The square brackets in your json mean that the property is a collection. It's a little unclear from your extract but I can think of two schemas that fit the sample you provided. Both successfully deserialize using the following code:
class Program
{
static async Task Main(string[] args)
{
var json = await File.ReadAllTextAsync("json1.json");
Body body = JsonConvert.DeserializeObject<Body>(json);
}
}
In the first, the two sxt_func_ack properties are different types:
public class Body
{
public Response Response { get; set; }
}
public class Response
{
public Class1 Sxt_func_ack { get; set; }
}
public class Class1
{
public IEnumerable<Class2> Sxt_func_ack { get; set; }
}
public class Class2
{
public int CoNo { get; set; }
public string Correlation_data { get; set; }
public string Data1 { get; set; }
public int ErrorNo { get; set; }
}
In the second, both sxt_func_ack properties are the same type:
public class Body
{
public Response Response { get; set; }
}
public class Response
{
public Class1 Sxt_func_ack { get; set; }
}
public class Class1
{
public IEnumerable<Class1> Sxt_func_ack { get; set; }
public int CoNo { get; set; }
public string Correlation_data { get; set; }
public string Data1 { get; set; }
public int ErrorNo { get; set; }
}
I have referred to this question, which is similar to my issue but unable to fix the issue completely since the data structure is different and I am not able to figure-out how to apply this solution to my example data given below:
{
"result": {
"RITM2572913": {
"number": "RITM2572913",
"state": "1",
"stage": "fulfillment",
"Sys_ID": "220e89681b31b384e3a0a79b2d4bcbf3",
"requested_for": "1d1673c4dbda5b0072a85099dc9619b0",
"Contoso_requested_for": "requested_for:1d1673c4dbda5b0072a85099dc9619b0,var_name_arr:",
"Contoso_sc_Purposeofthef5request": "Add",
"Contoso_Sc_Contactinfo": "Contact ",
"Contoso_sc_Appname": "Application ",
"Contoso_sc_Description": "Description",
"Contoso_special_instructions": "special_instructions:",
"business_justification": "Justification ",
"Contoso_business_justification": "busess_justification:Justification",
"Contoso_catalog_item_footer": "owner_info:"
}
}
}
I have the response data like this and need to de-serialize it to fit in the object model given below:
public class RITMGETRequestResponse
{
public RITMDetails result { get; set; }
public class RITMDetails
{
public string business_justification { get; set; }
public string number { get; set; }
public string requested_for { get; set; }
public string stage { get; set; }
public string state { get; set; }
public string Sys_ID { get; set; }
public string var_name_arr { get; set; }
public string Contoso_business_justification { get; set; }
public string Contoso_catalog_item_footer { get; set; }
public string Contoso_requested_for { get; set; }
public string Contoso_sc_Appname { get; set; }
public string Contoso_Sc_Contactinfo { get; set; }
public string Contoso_sc_Description { get; set; }
public string Contoso_sc_Purposeofthef5request { get; set; }
public string Contoso_special_instructions { get; set; }
}
}
In this case RITM number is dynamic. I need to get the Sys_ID and other properties of this JSON. How do I de-serialize this JSON response to get these values?
straightforward example:
used a JSONProperty attribute to map result values of a dynamic property name
class Program
{
static void Main(string[] args)
{
var deserialise = JsonConvert.DeserializeObject<RITMRequestResponse>("{\"result\": {\"123\" : { \"number\" : \"123\" }}}");
Console.WriteLine(deserialise);
Console.ReadLine();
}
}
public class RITMRequestResponse
{
[JsonProperty(PropertyName = "result")]
public Dictionary<string, RITMDetails> RITMDetails { get; set; }
}
public class RITMDetails
{
public string Number { get; set; }
}
I am getting json back from an http and I am trying to deserialized it into a C# object and it keeps coming back as null so my guess is that my data structure is off. Here is my code:
results = httpClient.GetStringAsync(url).Result;
var restResponse = new RestSharp.RestResponse();
restResponse.Content = results;
var deserializer = new JsonDeserializer();
var page = _deserializer.Deserialize<Tree>(restResponse);
Here is the Json:
{
"page":{
"results":[
{
"id":"144111690",
"type":"page",
"status":"current",
"title":"Title 1"
},
{
"id":"157540319",
"type":"page",
"status":"current",
"title":"Title 2"
},
{
"id":"144082624",
"type":"page",
"status":"current",
"title":"Title 3"
}
],
"start":0,
"limit":25,
"size":14
}
}
and Here are my C# objects:
public class Tree
{
public Results page { get; set; }
}
public class Results
{
public ResultDetails results { get; set; }
}
public class ResultDetails
{
public List<PageInfo> Pages { get; set; }
}
public class PageInfo
{
public long id { get; set; }
public string type { get; set; }
public string status { get; set; }
public string title { get; set; }
}
Can anyone advise on what is not "lining up" here?
Why don't you directly create class structure by using Visual studio ..that will give you class structure matching with your json.
you can check here how to generate : Visual Studio Generate Class From JSON or XML
Copy you json >> visual studio Edit menu > Paste Special >> Paste Json as class
This will work:
public class Tree
{
public Page page { get; set; }
}
public class Page
{
public List<Result> results { get; set; }
public int start { get; set; }
public int limit { get; set; }
public int size { get; set; }
}
public class Result
{
public string id { get; set; }
public string type { get; set; }
public string status { get; set; }
public string title { get; set; }
}
results is an array in JSON, but you defined it as an object (ResultDetails)
This might do the trick for you
public class Rootobject
{
[JsonProperty("page")]
public Page page { get; set; }
}
public class Page
{
[JsonProperty("results")]
public Result[] results { get; set; }
[JsonProperty("start")]
public int start { get; set; }
[JsonProperty("limit")]
public int limit { get; set; }
[JsonProperty("size")]
public int size { get; set; }
}
public class Result
{
[JsonProperty("id")]
public string id { get; set; }
[JsonProperty("type")]
public string type { get; set; }
[JsonProperty("status")]
public string status { get; set; }
[JsonProperty("title")]
public string title { get; set; }
}
And the implementation should be
results = httpClient.GetStringAsync(url).Result;
var restResponse = new RestSharp.RestResponse();
restResponse.Content = results;
var deserializer = new JsonDeserializer();
var page = _deserializer.Deserialize<Rootobject>(restResponse);