How do I create a Dictionary<string,string> for nested object - c#

I am retrieving the following JSON via a POST to an API
{
"State":"Andhra_Pradesh",
"District":"Guntur",
"Fact":"SELECT",
"Description":"",
"FactDate":"",
"FactNumber":"",
"FactType":"SELECT",
"Fact":{"Id":"1"}
}
I am able to execute the Ajax request via javascript, but I also want to consume the API through C# code.
I am using the below code, but I'm not quite sure on how to add the Fact object?
var values = new Dictionary<string, string>
{
{ "State", selectedState },
{ "District", selectedDistrict },
{ "Fact", ""},
{ "FactType", ""},
{ "FactNumber", ""},
{ "Description", ""},
{"Fact", "{Id,1}" },
{"FactDate", factDate.Date.ToString() }
};
using (var httpClient = new HttpClient())
{
var content = new FormUrlEncodedContent(values);
var response = await httpClient.PostAsync("http://api.in/" + "test", content);
}
How do I add the Fact object to Dictionary?

You'll probably need to define the data you are sending as actual class before using httpclient.
If you had only name value pairs then you could have used the NameValueCollection and sent as a formurlencoded but since you have a complex type, you might consider this below.
See below.
public class Rootobject
{
public string State { get; set; }
public string District { get; set; }
public Fact Fact { get; set; }
public string Description { get; set; }
public string CaseDate { get; set; }
public string FactNumber { get; set; }
public string FactType { get; set; }
}
public class Fact
{
public string Id { get; set; }
}
Usage is as below. be sure to include a reference to System.Net.Http.Formatting.dll
var client = new HttpClient();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var model = new Rootobject { State = "Andhra_Pradesh", District = "Guntur", FactType = "SELECT", Description = "", CaseDate = "", FactNumber = "", Fact = new Fact { Id = "1"} };
var data = await client.PostAsJsonAsync("http://api.in/" + "test", model);

I think this is just a json object, you can either create a class which have the same properties of (state, district etc ..) and use json serializer
or you can create JObject using Json.Net

You can use Newtonsonft.Json to to the serializaton/deserialization job and the code will be like that.
public class Rootobject
{
[JsonProperty("State")]
public string State { get; set; }
[JsonProperty("District")]
public string District { get; set; }
[JsonProperty("Fact")]
public Fact Fact { get; set; }
[JsonProperty("Description")]
public string Description { get; set; }
[JsonProperty("CaseDate")]
public string CaseDate { get; set; }
[JsonProperty("FactNumber")]
public string FactNumber { get; set; }
[JsonProperty("FactType")]
public string FactType { get; set; }
}
public class Fact
{
[JsonProperty("Id")]
public string Id { get; set; }
}
And then, after instatiating your object, just serialize it.
Rootobject example = new Rootobject();
//Add values to the variable example.
var objectSerialized = JsonConvert.SerializeObject(example);
After that, you will have a json ready to be send wherever you want.

Just change {"Fact", "{Id,1}" } to {"Fact.Id", "1" },

Related

Why is deserialized object fields are coming as null when data exists?

I have a json object that I need to deserialize, I'm using Json.NET to make these operations.
when it's a simple object, its quite easy to do it, but I cant figure out how to deserialize this string
json
{
"aspsp-list":
[
{
"id":"424250495054504C",
"bic":"BBPIPTPL",
"bank-code":"0010",
"aspsp-cde":"BBPI",
"name":"BANCO BPI, SA",
"logoLocation":"../img/corporate/theBank.jpg",
"api-list":[{
"consents":["BBPI/v1/consents"],
"payments":["BBPI/v1/payments"],
"accounts":["BBPI/v1/accounts"],
"funds-confirmations":["BBPI/v1/funds-confirmations"]
}]
},
{
"id":"544F54415054504C",
"bic":"TOTAPTPL",
"bank-code":"0018",
"aspsp-cde":"BST",
"name":"BANCO SANTANDER TOTTA, SA",
"logoLocation":"../img/openBank.svc",
"api-list":[{
"consents":["BBPI/v1/consents"],
"payments":["BBPI/v1/payments"],
"accounts":["BBPI/v1/accounts"],
"funds-confirmations":["BST/v1/funds-confirmations"]
}]
}
]
}
Now the code I have so far:
internal class AspspListResponseResource
{
// Report with the list of supported ASPSPs. Each ASPSP will include the list of available API endpoints and the logo.
[JsonProperty(PropertyName = "aspsp-list")]
public AspspList[] AspspList { get; set; }
public AspspListResponseResource() { /* Empty constructor to create the object */ }
public AspspListResponseResource(string jsonString)
{
//var alrr = JsonConvert.DeserializeObject<AspspListResponseResource>(jsonString);
JObject jObject = JObject.Parse(jsonString);
JToken jUser = jObject["aspsp-list"];
// The root object here is coming with certain fields as null, such as 'aspsp-cde', 'bank-code' and 'api-list'
AspspListResponseResource root = JsonConvert.DeserializeObject<AspspListResponseResource>(jsonString);
}
}
internal class Aspsp
{
// ASPSP Id
[JsonProperty(PropertyName = "id")]
public string Id { get; set; } = "";
// Bank Identifier Code
[JsonProperty(PropertyName = "bic")]
public string Bic { get; set; } = "";
// IBAN Bank Identifier
[JsonProperty(PropertyName = "bank-code")]
public string BankCode { get; set; } = "";
// ASPSP Code to use in the endpoint
[JsonProperty(PropertyName = "aspsp-cde")]
public string AspspCde { get; set; } = "";
// Institution name
[JsonProperty(PropertyName = "name")]
public string Name { get; set; } = "";
// Bank logo location
[JsonProperty(PropertyName = "logoLocation")]
public string LogoLocation { get; set; } = "";
// Bank Supported API List
[JsonProperty(PropertyName = "api-list")]
public ApiLink[] ApiList { get; set; }
}
internal class ApiLink
{
// Consents Link List
[JsonProperty(PropertyName = "consents")]
public string[] Consents { get; set; } = { "" };
// Payments Link List
[JsonProperty(PropertyName = "payments")]
public string[] Payments { get; set; } = { "" };
// Accounts Link List
[JsonProperty(PropertyName = "accounts")]
public string[] Accounts { get; set; } = { "" };
// Balances Link List
[JsonProperty(PropertyName = "balances")]
public string[] Balances { get; set; } = { "" };
// Transaction Link List
[JsonProperty(PropertyName = "transaction")]
public string[] Transaction { get; set; } = { "" };
// Funds-Confirmations Link List
[JsonProperty(PropertyName = "funds-confirmations")]
public string[] FundsConfirmations { get; set; } = { "" };
}
Sum of the values of the deserialized object are null, even though the jsonString definitelly has data.
How should I proceed here?
The way your json is structured:
{
"aspsp-list":
[
{
"id":"123123123",
"bic":"BBPIPTPL",
"bank-code":"0010",
"aspsp-cde":"BBPI",
"name":"BANCO BPI, SA",
"logoLocation":"../img/corporate/theBank.jpg",
"api-list":[{
"consents":"",
"payments":"",
"accounts":"",
"funds-confirmations":""
}]
},
{
"id":"1434231231",
"bic":"TOTAPTPL",
"bank-code":"0018",
"aspsp-cde":"BST",
"name":"BANCO SANTANDER TOTTA, SA",
"logoLocation":"../img/openBank.svc",
"api-list":[{
"consents":"",
"payments":"",
"accounts":"",
"funds-confirmations":""
}]
}
]
}
This is telling us that you have an object, with an array of objects called Aspsp-list.
If this is what you intended great.
We need to create an object similar to this
public class RootJsonObject {
public IEnumerable<Aspsp> Aspsp-list {get; set;}
}
To deserialize to this simply:
JsonConvert.Deserialize<RootJsonObject>(/*your json string*/ value);
If you wanted to only work with the array, you would need to deserialize purely to an IEnumerable/Array But you would also need to change your json to just be an array, not an object wrapping an array.
I managed to make it work now, my problem wasn't exactly that I couldn't deserialize because of data types or structure (at least not completely, comment that said that the structure was wrong was partly right).
So, this is how I solved the problem:
-> Created an empty costructor on the AspspListResponseResource class, so that the method JsonConvert.DeserializeObject<T>(jsonString) could create an instance of the object, I thought of this since the only constructor took a string, and so there was no other contructor for JsonConvert to use.
-> Put the field names of with help of [JsonProperty(PropertyName = "")], but this still gave me the deserialized object as null, or with some null fields.
-> commented the fields Transaction and FundsConfirmations of the ApiLink class, these fields were in the documentation of the Web API so I put them in, but looking at the json string I recieve, it look like they aren't being used, so I just commented them
and after these changes the code now works flawlessly:
The code:
internal class AspspListResponseResource
{
// Report with the list of supported ASPSPs. Each ASPSP will include the list of available API endpoints and the logo.
[JsonProperty(PropertyName = "aspsp-list")]
public Aspsp[] AspspList { get; set; }
public AspspListResponseResource() { /* Empty constructor to create the object */ }
public AspspListResponseResource(string jsonString)
{
AspspListResponseResource root = JsonConvert.DeserializeObject<AspspListResponseResource>(jsonString);
this.AspspList = root.AspspList;
}
}
internal class Aspsp
{
// ASPSP Id
[JsonProperty(PropertyName = "id")]
public string Id { get; set; } = "";
// Bank Identifier Code
[JsonProperty(PropertyName = "bic")]
public string Bic { get; set; } = "";
// IBAN Bank Identifier
[JsonProperty(PropertyName = "bank-code")]
public string BankCode { get; set; } = "";
// ASPSP Code to use in the endpoint
[JsonProperty(PropertyName = "aspsp-cde")]
public string AspspCde { get; set; } = "";
// Institution name
[JsonProperty(PropertyName = "name")]
public string Name { get; set; } = "";
// Bank logo location
[JsonProperty(PropertyName = "logoLocation")]
public string LogoLocation { get; set; } = "";
// Bank Supported API List
[JsonProperty(PropertyName = "api-list")]
public ApiLink[] ApiList { get; set; }
}
internal class ApiLink
{
// Consents Link List
[JsonProperty(PropertyName = "consents")]
public string[] Consents { get; set; } = { "" };
// Payments Link List
[JsonProperty(PropertyName = "payments")]
public string[] Payments { get; set; } = { "" };
// Accounts Link List
[JsonProperty(PropertyName = "accounts")]
public string[] Accounts { get; set; } = { "" };
// Balances Link List
[JsonProperty(PropertyName = "balances")]
public string[] Balances { get; set; } = { "" };
//// Transaction Link List
//[JsonProperty(PropertyName = "transaction")]
//public string[] Transaction { get; set; } = { "" };
//
//// Funds-Confirmations Link List
//[JsonProperty(PropertyName = "funds-confirmations")]
//public string[] FundsConfirmations { get; set; } = { "" };
}
You need to create a contructor for the ApiLink class so you can do the following:
var apiListRaw = new ApiLink(value["api-list"][0] as JObject);
The constructor would look something like the following:
public ApiLink(JObject json)
{
Consensts = (string[])json["consents"];
...
}

Json Deserialise return null when convert to list of object in c# [duplicate]

This question already has answers here:
Private setters in Json.Net
(5 answers)
Closed 4 years ago.
I am trying to deserialise the json into custom class list using Newtonsoft.Json.
Here is my code:
public List<EmployeeModel> getEmployee()
{
string Baseurl = "http://dummy.restapiexample.com/api/v1/";
using (var client = new HttpClient())
{
//Passing service base url
client.BaseAddress = new Uri(Baseurl);
client.DefaultRequestHeaders.Clear();
//Define request data format
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//Sending request to find web api REST service resource GetAllEmployees using HttpClient
var EmpResponse = new List<EmployeeModel>();
var Res = client.GetAsync("employees");
Res.Wait();
var result = Res.Result;
//Checking the response is successful or not which is sent using HttpClient
if (result.IsSuccessStatusCode)
{
//Storing the response details recieved from web api
var r = result.Content.ReadAsStringAsync().Result;
EmpResponse = JsonConvert.DeserializeObject<List<EmployeeModel>>(r);
//Deserializing the response recieved from web api and storing into the Employee list
}
//returning the employee list to view
return EmpResponse;
}
}
When I check the variable r value I am getting following Json String:
[
{
"id": "317",
"employee_name": "Nitza",
"employee_salary": "775",
"employee_age": "1",
"profile_image": ""
},
{
"id": "318",
"employee_name": "Nitza Ivri",
"employee_salary": "10000",
"employee_age": "33",
"profile_image": ""
}
]
Also, my model code is as per below:
public class EmployeeModel
{
public string id { get; private set; }
public string employee_name { get; private set; }
public string employee_salary { get; private set; }
public string employee_age { get; private set; }
}
The reason is that your properties in EmployeeModel has private set. You need to remove private from your properties then it would be able to deserialize successfully. Your entity should be like following:
public class EmployeeModel
{
public string id { get; set; }
public string employee_name { get; set; }
public string employee_salary { get; set; }
public string employee_age { get; set; }
}
Also, your EmployeeModel does not contain property profile_image. You need to add this property to your model.
If it is important for you to keep your properties setters as private, you can provide a constructor that has parameters like:
public class EmployeeModel
{
public EmployeeModel(string id, string employee_name,string employee_salary, string employee_age, string profile_image )
{
this.id = id;
this.employee_name = employee_name;
this.employee_salary = employee_salary;
this.employee_age = employee_age;
this.profile_image = profile_image;
}
public string id { get; private set; }
public string employee_name { get; private set; }
public string employee_salary { get; private set; }
public string employee_age { get; private set; }
public string profile_image { get; private set; }
}

JSON to object C# (mapping complex API response to C# object)

I am able to handle simple JSON serialization and deserialization but this API response seems little complicated, and I am seeking an advice as to what would be ideal approach to tackle this.
I'm trying to call an API for MVC application.
Goal is to map API data to model.
API endpoint is
https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=1min&apikey=MyAPIKey
Troubles here are:
JSON data keys have white space in them.
When I tried doing paste special in Visual studio, It gave me a long
list of classes for each date entry separately, because this API
call returns a separate set of information for date.
To solve problem explained in point 1, I used [JsonProperty("1. Information")] in class. And in my code..
public async Task TSI()
{
HttpClient client = new HttpClient();
//Uri uri = new Uri("http://date.jsontest.com/");
Uri uri = new Uri("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=5min&apikey=demo");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)
{
dynamic result = await response.Content.ReadAsAsync<object>();
IEnumerable<dynamic> dObj = JsonConvert.DeserializeObject<dynamic>(result.ToString());
IEnumerable<dynamic> t1 = dObj.FirstOrDefault();
IEnumerable<dynamic> t2 = dObj.LastOrDefault();
dynamic MetaData = t1.FirstOrDefault();
Rootobject ro = new Rootobject();
ro.MetaData = MetaData;
}
PS: I'm relatively new to make API calls and handling them.
I was able to make a call to
date.jsontest.com
and map the API data to model (which I had created using paste special)
//API response
{
"time": "12:53:22 PM",
"milliseconds_since_epoch": 1504875202754,
"date": "09-08-2017"
}
//C# code to map to API data
public class sampleObject
{
public string time { get; set; }
public long milliseconds_since_epoch { get; set; }
public string date { get; set; }
}
My RootObject looks like this:
public class Rootobject
{
[JsonProperty("Meta Data")]
public MetaData MetaData { get; set; }
[JsonProperty("Time Series (1min)")]
public TimeSeries1Min TimeSeries1min { get; set; }
}
public class MetaData
{
[JsonProperty("1. Information")]
public string _1Information { get; set; }
[JsonProperty("2. Symbol")]
public string _2Symbol { get; set; }
[JsonProperty("3. Last Refreshed")]
public string _3LastRefreshed { get; set; }
[JsonProperty("4. Interval")]
public string _4Interval { get; set; }
[JsonProperty("5. Output Size")]
public string _5OutputSize { get; set; }
[JsonProperty("6. Time Zone")]
public string _6TimeZone { get; set; }
}
// I have so many of these sub-classes for dates, which again is an issue
public class TimeSeries1Min
{
public _20170907160000 _20170907160000 { get; set; }
public _20170907155900 _20170907155900 { get; set; }
....
....}
public class _20170907160000
{
public string _1open { get; set; }
public string _2high { get; set; }
public string _3low { get; set; }
public string _4close { get; set; }
public string _5volume { get; set; }
}
public class _20170907155900
{
public string _1open { get; set; }
public string _2high { get; set; }
public string _3low { get; set; }
public string _4close { get; set; }
public string _5volume { get; set; }
}
It is hard to create a model from this json, but you can convert those data to dictionary
var jObj = JObject.Parse(json);
var metadata = jObj["Meta Data"].ToObject<Dictionary<string, string>>();
var timeseries = jObj["Time Series (1min)"].ToObject<Dictionary<string, Dictionary<string, string>>>();
The following code should do what you want
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
var obj = JsonConvert.DeserializeObject<Rootobject>(result);
//No idea what you want to do with this line as there is no MetaData property on the root object
obj.MetaData = MetaData;
}

How to design class for abstract json document?

Suppose we have class Request which we want to serialize to json and deserialize from json.
class Request {
public string SessionId { get; set; }
...
public string InnerJson { get; set; }
}
As json it should looks like
{
"SessionId": 1,
...
"InnerJson": {
"some": "json object",
"whatever": 666
}
}
InnerJson is some json document (arbitrary type).
Is it good to use string for InnerJson in Request?
Is there any good way to design Request class?
If you are going for a strongly typed model I'd suggest a factory. For demonstration sake:
public abstract class AbstractOptions { }
public class Options1 : AbstractOptions { public int Whatever { get; set; } }
public class Options2 : AbstractOptions { public string Some { get; set; } }
public class Options3 : AbstractOptions {
[JsonProperty("when")] public DateTime When { get; set; }
[JsonProperty("inner")] public InnerComplexObject Inner { get; set; }
}
public class Request {
[JsonProperty("session-id")] public string SessionId { get; set; }
[JsonProperty("options")] public AbstractOptions Options { get; set; }
}
public class InnerComplexObject { }
then use it like:
var req1 = new Request() { SessionId = "s1", Options = new Options1 { Whatever = 123 } };
var req2 = new Request() { SessionId = "s2", Options = new Options2 { Some = "some" } };
var req3 = new JToken.Request() { SessionId = "s3", Options = new Options3 { When = DateTime.UtcNow, Inner = new InnerComplexObject() } };
Otherwise, for flexibility, keep InnerJson a string and use dynamic queries.

Deserialize nested JSON Response with RestSharp Client

I'd like to consume a REST Api and deserialize the nested JSON Response. For that purpose I tried to create some POCO classes which represent the JSON Response [1].
The response looks like this:
{
"success": true,
"message": "OK",
"types":
[
{
"name": "A5EF3-ASR",
"title": "ITIL Foundation Plus Cloud Introduction",
"classroomDeliveryMethod": "Self-paced Virtual Class",
"descriptions": {
"EN": {
"description": "some Text null",
"overview": null,
"abstract": "Some other text",
"prerequisits": null,
"objective": null,
"topic": null
}
},
"lastModified": "2014-10-08T08:37:43Z",
"created": "2014-04-28T11:23:12Z"
},
{
"name": "A4DT3-ASR",
"title": "ITIL Foundation eLearning Course + Exam",
"classroomDeliveryMethod": "Self-paced Virtual Class",
"descriptions": {
"EN": {
"description": "some Text"
(...)
So I created the following POCO classes:
public class Course
{
public bool success { get; set; }
public string Message { get; set; }
public List<CourseTypeContainer> Type { get; set; }
}
/* each Course has n CourseTypes */
public class CourseType
{
public string Name { get; set; }
public string Title { get; set; }
public List<CourseTypeDescriptionContainer> Descriptions { get; set; }
public DateTime LastModified { get; set; }
public DateTime Created { get; set; }
}
public class CourseTypeContainer
{
public CourseType CourseType { get; set; }
}
/* each CourseType has n CourseTypeDescriptions */
public class CourseTypeDescription
{
public string Description { get; set; }
public string Overview { get; set; }
public string Abstract { get; set; }
public string Prerequisits { get; set; }
public string Objective { get; set; }
public string Topic { get; set; }
}
public class CourseTypeDescriptionContainer
{
public CourseTypeDescription CourseTypeDescription { get; set; }
}
And this is the API Code:
var client = new RestClient("https://www.someurl.com");
client.Authenticator = new HttpBasicAuthenticator("user", "password");
var request = new RestRequest();
request.Resource = "api/v1.0/types";
request.Method = Method.GET;
request.RequestFormat = DataFormat.Json;
var response = client.Execute<Course>(request);
EDIT 1: I found a Typo, the Type property in AvnetCourse should be named Types:
public List<AvnetCourseTypeContainer> Type { get; set; } // wrong
public List<AvnetCourseTypeContainer> Types { get; set; } // correct
Now the return values look like:
response.Data.success = true // CORRECT
repsonse.Data.Message = "OK" // CORRECT
response.Data.Types = (Count: 1234); // CORRECT
response.Data.Types[0].AvnetCourseType = null; // NOT CORRECT
EDIT 2: I implemented the Course.Types Property using a List<CourseType> instead of a List<CourseTypeContainer>, as proposed by Jaanus. The same goes for the CourseTypeDescriptionContainer:
public List<CourseTypeContainer> Type { get; set; } // OLD
public List<CourseTypeDescriptionContainer> Descriptions { get; set; } // OLD
public List<CourseType> Type { get; set; } // NEW
public List<CourseTypeDescription> Descriptions { get; set; } // NEW
Now the response.Data.Types finally are properly filled. However, the response.Data.Types.Descriptions are still not properly filled, since there is an additional language layer (e.g. "EN"). How can I solve this, without creating a PACO for each language?
EDIT 3: I had to add an additional CourseTypeDescriptionDetails class, where I would store the descriptive Data. In my CourseTypeDescription I added a property of the Type List for each language. Code Snippet:
public class AvnetCourseType
{
public List<CourseTypeDescription> Descriptions { get; set; }
// other properties
}
public class CourseTypeDescription
{
public List<CourseTypeDescriptionDetails> EN { get; set; } // English
public List<CourseTypeDescriptionDetails> NL { get; set; } // Dutch
}
public class CourseTypeDescriptionDetails
{
public string Description { get; set; }
public string Overview { get; set; }
public string Abstract { get; set; }
public string Prerequisits { get; set; }
public string Objective { get; set; }
public string Topic { get; set; }
}
It works now, but I need to add another property to CourseTypeDescription for each language.
OLD: The return values are
response.Data.success = true // CORRECT
repsonse.Data.Message = "OK" // CORRECT
response.Data.Type = null; // WHY?
So why does my response.Type equal null? What am I doing wrong?
Thank you
Resources:
[1] RestSharp Deserialization with JSON Array
Try using this as POCO:
public class Course
{
public bool success { get; set; }
public string message { get; set; }
public List<CourseTypeContainer> Types { get; set; }
}
Now you have list of CourseTypeContainer.
And CourseTypeContainer is
public class CourseTypeContainer
{
public CourseType CourseType { get; set; }
}
So when you are trying to get response.Data.Types[0].AvnetCourseType , then you need to have field AvnetCourseType inside CourseTypeContainer
Or I think what you want is actually this public List<CourseType> Types { get; set; }, you don't need a container there.
Just in case this helps someone else, I tried everything here and it still didn't work on the current version of RestSharp (106.6.2). RestSharp was completely ignoring the RootElement property as far as I could tell, even though it was at the top level. My workaround was to manually tell it to pull the nested JSON and then convert that. I used JSON.Net to accomplish this.
var response = restClient.Execute<T>(restRequest);
response.Content = JObject.Parse(response.Content)[restRequest.RootElement].ToString();
return new JsonDeserializer().Deserialize<T>(response);
I used http://json2csharp.com/ to create C# classes from JSON.
Then, renamed RootObject to the ClassName of the model file I'm creating
All the data in the nested json was accessible after RestSharp Deserializitaion similar to responseBody.data.Subject.Alias
where data, Subject and Alias are nested nodes inside the response JSON received.

Categories