How to parse JSON data having dot(.) operator? [duplicate] - c#

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

Related

Deserializing JSON into C# Object

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

Deserialize nested JSON, C# [duplicate]

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

Deserialize Newtonsoft Json data with Dynamic property name - C#

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

How to deserialize JSON to .NET object using JSON.NET?

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

Need help Serializing/Deserializing this JSON

I have this simple JSON and I was making deserializing this JSON, so I can get the elements. This is the JSON I have :
{
"QuestionIDs": [
"QID1",
"QID3"
],
"QuestionDefinitions": {
"Question1": {
"DETag": "Q1",
"Config": {
"QDescription": "UseText"
},
"COrder": [
"1",
"2",
"3"
],
"Validation": {
"Settings": {
"ForceResponse": "OFF",
"ForceResponseType": "ON",
"Type": "None"
}
}
}
},
"NextButton": null,
"PreviousButton": false
}
This is the code I've written :
[DataContract]
public class RootObject
{
[DataMember]
public Dictionary<string, Dictionary<string, string>> QuestionDefinitions { get; set; }
[DataMember]
public List<string> QuestionIDs { get; set; }
}
QuestionIDs is working just fine. But, QuestionDefinitions isn't working. It says that it is an empty sequence. I'm not sure what's wrong.
I want to be able to access QuestionDefinitions.
I tried with Json.Net. Facing the same issue. I was able to get the simple elements that are out. But, couldn't get to access the QuestionDefinitions.
Any help would be appreciated.
EDIT :
I also tried implementing this class like this :
[DataContract]
public class QuestionDetails
{
[DataMember]
public string DETag { get; set; }
[DataMember]
[DataMember]
public List<Configuration> Config { get; set; }
[DataMember]
public List<string> ChoiceOrder { get; set; }
[DataMember]
public List<Validation> Validation { get; set; }
[DataMember]
public List<string> COrder { get; set; }
[DataMember]
public string NextButton { get; set; }
[DataMember]
public string PreviousButton { get; set; }
}
[DataContract]
public class RootObject
{
[DataMember]
public Dictionary<string, QuestionDetails> QuestionDefinitions { get; set; }
[DataMember]
public List<string> QuestionIDs { get; set; }
}
Your class strucutre against the JSON getting returned is not correct.
When pasted your JSON in json2csharp.com the following the POCO class which generated:
public class Config
{
public string QDescription { get; set; }
}
public class Settings
{
public string ForceResponse { get; set; }
public string ForceResponseType { get; set; }
public string Type { get; set; }
}
public class Validation
{
public Settings Settings { get; set; }
}
public class Question1
{
public string DETag { get; set; }
public Config Config { get; set; }
public List<string> COrder { get; set; }
public Validation Validation { get; set; }
}
public class QuestionDefinitions
{
public Question1 Question1 { get; set; }
}
public class RootObject
{
public List<string> QuestionIDs { get; set; }
public QuestionDefinitions QuestionDefinitions { get; set; }
public object NextButton { get; set; }
public bool PreviousButton { get; set; }
}
Now using the above class as representation of your JSON structure you should be able to deserialize it in to C# object.
The following line of code would do it using NewtonSoft library:
string json = "your json result";
RootObject result = JsonConvert.DeserializeObject<RootObject>(json);
You can even do it from within Visual Studio if you have 2013 or above doing like following as described in this post:
Hope it helps.
Changing a little the code in #EhsanSajjad's answer, maybe you could use something like:
public class Config
{
public string QDescription { get; set; }
}
public class Settings
{
public string ForceResponse { get; set; }
public string ForceResponseType { get; set; }
public string Type { get; set; }
}
public class Validation
{
public Settings Settings { get; set; }
}
public class Question
{
public string DETag { get; set; }
public Config Config { get; set; }
public List<string> COrder { get; set; }
public Validation Validation { get; set; }
}
public class RootObject
{
public List<string> QuestionIDs { get; set; }
public Dictionary<string, Question> QuestionDefinitions { get; set; }
public object NextButton { get; set; }
public bool PreviousButton { get; set; }
}
Try this model
public class RootObject
{
public List<string> QuestionIDs { get; set; }
public QuestionDefinitions QuestionDefinitions { get; set; }
public object NextButton { get; set; }
public bool PreviousButton { get; set; }
}
public class QuestionDefinitions
{
public Question1 Question1 { get; set; }
public List<string> COrder { get; set; }
public Validation Validation { get; set; }
}
public class Question1 {
public string DETag { get; set; }
public Config Config { get; set; }
}
public class Config {
public string QDescription { get; set; }
}
public class Validation {
public Settings Settings { get; set; }
}
public class Settings
{
public string ForceResponse { get; set; }
public string ForceResponseType { get; set; }
public string Type { get; set; }
}

Categories

Resources