Hello I have serious issues with populating my JSON file to C# object, because JSON contains "array of arrays of arrays". I need to create class with all the arrays to be able load the files there after deserialize, but i have no idea how to create structure like that.
JSON file:
{
"status": true,
"result": [
{
"ID": "1",
"UserID": "1001",
"web_id": "2753",
"certificate_id": "31",
"domain": "testsomething.com",
"status": "ssl_uninstalling",
"updated_at": "2017-02-15 15:08:04",
"IP": "xx.x.xxx.xxx",
"OS_version": "CentOS release 4.8"
},
{
"ID": "2",
"UserID": "1001",
"web_id": "2753",
"certificate_id": "31",
"domain": "admin.testsomething.com",
"status": "ssl_uninstalling",
"updated_at": "2017-02-13 14:19:45",
"IP": "xx.x.xxx.xxx",
"OS_version": "CentOS release 4.8"
},
{
"ID": "3",
"UserID": "1001",
"web_id": "2753",
"certificate_id": "31",
"domain": "www.testsomething16.com",
"status": "ssl_uninstalling",
"updated_at": "2017-02-16 16:22:40",
"IP": "xx.x.xxx.xxx",
"OS_version": "CentOS release 4.8"
},
{
"ID": "4",
"UserID": "1001",
"web_id": "2753",
"certificate_id": "31",
"domain": "blog.testsomething.com",
"status": "ssl_uninstalling",
"updated_at": "2017-02-16 16:22:40",
"IP": "xx.x.xxx.xxx",
"OS_version": "CentOS release 4.8"
}
],
"errors": []
}
The structure for your json might look like
public class Result
{
[JsonProperty("ID")]
public string ID { get; set; }
[JsonProperty("UserID")]
public string UserID { get; set; }
[JsonProperty("web_id")]
public string web_id { get; set; }
[JsonProperty("certificate_id")]
public string certificate_id { get; set; }
[JsonProperty("domain")]
public string domain { get; set; }
[JsonProperty("status")]
public string status { get; set; }
[JsonProperty("updated_at")]
public string updated_at { get; set; }
[JsonProperty("IP")]
public string IP { get; set; }
[JsonProperty("OS_version")]
public string OS_version { get; set; }
}
public class Rootobject
{
[JsonProperty("status")]
public bool status { get; set; }
[JsonProperty("result")]
public List<Result> result { get; set; }
[JsonProperty("errors")]
public List<object> errors { get; set; }
}
You can use Visual Studio to create classes for you out of JSON.
Copy your JSON in the clipboard. that means just CTRL + C and then go to Visual Studio Edit -> Paste Special -> Paste JSON As Classes
Another way out to create class sturcture for your JSON could be you can go to json2csharp: generate c# classes from json and create the classes.
I think you can create a model like below:
public class Example
{
public bool Status { get; set; }
public ResultModel ResultModel { get; set; }
public bool Error { get; set; }
public Example()
{
ResultModel = new ResultModel();
}
}
public class ResultModel
{
public int ID { get; set; }
public int UserId { get; set; }
public int WebId { get; set; }
}
Related
Can you give me an example how to write a method in c# to map products from a Json file and match the group name by productId from a different file? I just want to output the results to look something like this
{
"Category": "Shoes",
"AsOfDate": "12/02/2021",
"Quotes": [
{
"ProductId": "Shoe 1",
"AsOfDate": "12/02/2021",
"Value": 11481.99
},
{
"ProductId": "Shoe 2",
"AsOfDate": "12/02/2021",
"Value": 5534.99
},
{
"ProductId": "Shoe 3",
"AsOfDate": "12/02/2021",
"Value": 4753.99
}]
}
[Name("ProductId")]
public string ProductId { get; set; }
[Name("Date")]
public DateTime Date { get; set; }
[Name("Price")]
public decimal Price { get; set; }
public string Category { get; set; }
public string ProductId { get; set; }
public IEnumerable<QuotesModel> Quotes { get; set; }
Add the following model to your project
public class Rootobject
{
public string Category { get; set; }
public string AsOfDate { get; set; }
public Quote[] Quotes { get; set; }
}
public class Quote
{
public string ProductId { get; set; }
public string AsOfDate { get; set; }
public float Value { get; set; }
}
then you could deserialize your JSON file like this
string jsonString = File.ReadAllText("fileName.tex");
Rootobject rootobject = JsonSerializer.Deserialize<Rootobject>(jsonString);
don't forget, use this name spaces
using System.Text.Json;
using System.IO;
Read more on How to serialize and deserialize JSON in .NET
Product Json is like
[
{
"ProductId": "EU9012 Curncy",
"AsOfDate": "2019-12-31T00:00:00",
"Value": 4741.99
},
{
"ProductId": "EU2026 Govt",
"AsOfDate": "2019-12-31T00:00:00",
"Value": 1432.99
},
{
"ProductId": "EU2020 Curncy",
"AsOfDate": "2019-12-31T00:00:00",
"Value": 4356.99
},
]
And Category Json looks like
[
{
"GroupName": "Shoes",
"ProductId": "EUCF101",
"Quotes": null
},
{
"GroupName": "Tshirts",
"ProductId": "EUCF1010",
"Quotes": null
},
{
"GroupName": "Jeans",
"ProductId": "EUCF1012",
"Quotes": null
},
]
And i need a method to create a single json to output quotes for each category based on productId match
The problem I am facing is that I am getting 0's for the values I ask for in the JSON.
I recently asked a question here about getting specific values from a JSON array response that come from an API.
Now I have a new JSON response from a different route and in there I want one values and its called EntityId its places in a block of Entity See the code for more details, I would like to grab that from this response and place them in a list or Array because it tells me who submitted the assignment in D2L.
UPDATE- After getting comments from a user I used JSON to C# tool to create the full class with all the values but I still get the values as 0,0,0,0.
Right now I am getting 0,0,0,0 values and not getting the actual values if it's possible I would like to grab the whole block on Entity.
JSON
[
{
"Entity": {
"DisplayName": "FullName",
"EntityId": 123,
"EntityType": "User",
"Active": true
},
"Status": 1,
"Feedback": null,
"Submissions": [
{
"Id": 27,
"SubmittedBy": {
"Identifier": "123",
"DisplayName": "FullName"
},
"SubmissionDate": "2019-08-01T15:25:04.130Z",
"Comment": {
"Text": "",
"Html": ""
},
"Files": [
{
"IsRead": false,
"IsFlagged": false,
"IsDeleted": false,
"FileId": 1245,
"FileName": "1.2.10.png",
"Size": 144407
},
{
"IsRead": false,
"IsFlagged": false,
"IsDeleted": false,
"FileId": 292,
"FileName": "1.3.8.png",
"Size": 127869
}
]
}
],
"CompletionDate": "2019-08-01T15:25:04.130Z"
},
{
"Entity": {
"DisplayName": "FullName",
"EntityId": 123,
"EntityType": "User",
"Active": true
},
"Status": 1,
"Feedback": null,
"Submissions": [
{
"Id": 41,
"SubmittedBy": {
"Identifier": "123",
"DisplayName": "FullName"
},
"SubmissionDate": "2019-08-03T03:31:43.807Z",
"Comment": {
"Text": " \nAlex",
"Html": "<p></p>\n<p>Alex</p>"
},
"Files": [
{
"IsRead": false,
"IsFlagged": false,
"IsDeleted": false,
"FileId": 313,
"FileName": "Capture 1.2.10 Questions.PNG",
"Size": 97722
}
]
}
],
"CompletionDate": "2019-08-03T03:31:43.807Z"
}
]
Classes:
public class Entity
{
public string DisplayName { get; set; }
public int EntityId { get; set; }
public string EntityType { get; set; }
public bool Active { get; set; }
}
public class SubmittedBy
{
public string Identifier { get; set; }
public string DisplayName { get; set; }
}
public class Comment
{
public string Text { get; set; }
public string Html { get; set; }
}
public class File
{
public bool IsRead { get; set; }
public bool IsFlagged { get; set; }
public bool IsDeleted { get; set; }
public int FileId { get; set; }
public string FileName { get; set; }
public int Size { get; set; }
}
public class Submission
{
public int Id { get; set; }
public SubmittedBy SubmittedBy { get; set; }
public DateTime SubmissionDate { get; set; }
public Comment Comment { get; set; }
public IList<File> Files { get; set; }
}
public class Example
{
public Entity Entity { get; set; }
public int Status { get; set; }
public object Feedback { get; set; }
public IList<Submission> Submissions { get; set; }
public DateTime CompletionDate { get; set; }
}
Code:
var request = new RestRequest(string.Format(Link));
request.Method = Method.GET;
authenticator.Authenticate(client, request);
var response = client.Execute(request);
var thisasa = JsonConvert.DeserializeObject<List<Example>>
(response.Content).Select(
o => o.Identifier).ToList();
The Example data model shown in your question already can be used to successfully deserialize the JSON shown. All that's left is to pick out the Entity.EntityId property via a Select:
var thisasa = JsonConvert.DeserializeObject<List<Example>>(response.Content)
.Select(o => o.Entity.EntityId)
.ToList();
Demo fiddle #1 here.
Incidentally, if you only need Entity.EntityId you could simplify your data model as follows:
public class Entity
{
public int EntityId { get; set; }
}
public class Example
{
public Entity Entity { get; set; }
}
Demo fiddle #2 here.
(As an aside, since your Example class corresponds to the documented object Dropbox.EntityDropbox, you might want to rename your type to EntityDropbox for clarity.)
I have to:
DeserializeObject - do some changes - SerializeObject
When my Json have miltiple types e.g.
{
"type": "test",
"currentStatus": "Active",
"id": "987",
"items": [
{
"type": "test1",
"id": "123",
"name": "Segment Members",
"memberCount": "0",
"outputTerminals": [
{
"type": "test2",
"id": "123",
"connectedId": "123",
"terminalType": "out"
}
],
"position": {
"type": "Position",
"x": "46",
"y": "14"
},
"isFinished": "true",
"isRecurring": "false",
"segmentId": "123"
},
{
"type": "test5",
"id": "1390",
"name": "Yay! Clickers",
"memberCount": "2",
"position": {
"type": "Position",
"x": "330",
"y": "375"
},
"waitFor": "2592000"
},
{
"type": "test3",
"id": "1391",
"name": "test",
"memberCount": "73",
"outputTerminals": [
{
"type": "test4",
"id": "123",
"connectedId": "123",
"connectedType": "CampaignWaitAction",
"terminalType": "yes"
},
{
"type": "test4",
"id": "123",
"connectedId": "123",
"connectedType": "CampaignWaitAction",
"terminalType": "no"
}
],
"position": {
"type": "Position",
"x": "123",
"y": "123"
},
"testId": "123"
}
]
}
What data type i should use for this operation? dynamic, object, Jobject...? or maybe something else?
I would just create an object and deseriablize it to that type. A lot easier than doing it dynamically. (assuming it will stay in that structure always)
WHAT TO DO
Copy your Json:
`Edit` -> `Paste Special` -> `Paste JSON As CLASSES`
And there you go! You have the Type you want to deserialize to.
var deserializedJson = JsonConvert.DeserializeObject<YourNewObject>(jsonString);
Note: if the pasting of the json class doesn't work, make sure your json is valid: ClickHereToValidateJson
using Newtonsoft.Json;
dynamic collection = new
{
MultipleType = //call function which returns json here
};
//serialize
var jsonSerializedFeed = JsonConvert.SerializeObject(MultipleType);
//deserialize
var jsonSerializedFeed = JsonConvert.DeserializeObject(MultipleType);
Hope it helps
You can create classes and serialize/deserialize json:
public class OutputTerminal
{
public string type { get; set; }
public string id { get; set; }
public string connectedId { get; set; }
public string terminalType { get; set; }
public string connectedType { get; set; }
}
public class Position
{
public string type { get; set; }
public string x { get; set; }
public string y { get; set; }
}
public class Item
{
public string type { get; set; }
public string id { get; set; }
public string name { get; set; }
public string memberCount { get; set; }
public IList<OutputTerminal> outputTerminals { get; set; }
public Position position { get; set; }
public string isFinished { get; set; }
public string isRecurring { get; set; }
public string segmentId { get; set; }
public string waitFor { get; set; }
public string testId { get; set; }
}
public class Root
{
public string type { get; set; }
public string currentStatus { get; set; }
public string id { get; set; }
public IList<Item> items { get; set; }
}
And then:
string json = JsonConvert.SerializeObject(rootObject);
Root root = JsonConvert.DeserializeObject<Root>(json);
Also, you can use dynamic type without classes:
string json = JsonConvert.SerializeObject(dynamicObject);
dynamic obj = JsonConvert.DeserializeObject(json);
Im trying to learn RavenDB in an MVC-project...Lets say we have many documents stored i a RavenDB collection looking something like this:
"ShipVia": "shippers/2",
"Freight": 18.66,
"Lines": [
{
"Product": "products/25",
"ProductName": "NuNuCa Nuß-Nougat-Creme",
},
I have managed to display a singe property (for example "Freight") by doing this:
Class:
public class Orders
{
public string Freight { get; set; }
}
Then create a hard-typed view with a List-template...That gives me all the Freights-property in the database...
I would like to get a hold of the "Lines"-property and be able to see product and product-name...Tried this:
namespace World.DAL
{
public class Orders
{
public string Company { get; set; }
public string Employee { get; set; }
public List<Lines> Lines { get; set; }
}
public class Lines
{
public string Product { get; set; }
public string ProductName { get; set; }
}
}
That did notwork..Just returned an emptly list I think..Can someone point me in the right direction?
EDIT:
{
"Company": "companies/65",
"Employee": "employees/5",
"OrderedAt": "1997-12-02T00:00:00.0000000",
"RequireAt": "1997-12-30T00:00:00.0000000",
"ShippedAt": "1997-12-08T00:00:00.0000000",
"ShipTo": {
"Line1": "2817 Milton Dr.",
"Line2": null,
"City": "Albuquerque",
"Region": "NM",
"PostalCode": "87110",
"Country": "USA"
},
"ShipVia": "shippers/2",
"Freight": 18.66,
"Lines": [
{
"Product": "products/25",
"ProductName": "NuNuCa Nuß-Nougat-Creme",
"PricePerUnit": 14.0,
"Quantity": 35,
"Discount": 0.25
},
{
"Product": "products/75",
"ProductName": "Rhönbräu Klosterbier",
"PricePerUnit": 7.75,
"Quantity": 18,
"Discount": 0.0
}
]
}
Your class needs to match the json format exactly, which means your class needs to look like this:
public class Orders
{
public string ShipVia { get; set; }
public string Freight { get; set; }
public List<Lines> Lines { get; set; }
}
Of course your lines class still needs to be declared
public class Lines
{
public string Product { get; set; }
public string ProductName { get; set; }
}
I am trying to turn a json response back from foursquare into objects. I get something like this back
{
"meta":{
"code":200
},
"response":{
"venues":[
{
"id":"4abfb58ef964a520be9120e3",
"name":"Costco",
"contact":{
"phone":"6045967435",
"formattedPhone":"(604) 596-7435"
},
"location":{
"address":"7423 King George Hwy",
"crossStreet":"btw 76 Avenue & 73A Avenue",
"lat":49.138259617056015,
"lng":-122.84723281860352,
"distance":19000,
"postalCode":"V3W 5A8",
"city":"Surrey",
"state":"BC",
"country":"Canada",
"cc":"CA"
},
"canonicalUrl":"https:\/\/foursquare.com\/v\/costco\/4abfb58ef964a520be9120e3",
"categories":[
{
"id":"4bf58dd8d48988d1f6941735",
"name":"Department Store",
"pluralName":"Department Stores",
"shortName":"Department Store",
"icon":{
"prefix":"https:\/\/foursquare.com\/img\/categories_v2\/shops\/departmentstore_",
"suffix":".png"
},
"primary":true
}
],
"verified":true,
"restricted":true,
"stats":{
"checkinsCount":2038,
"usersCount":533,
"tipCount":12
},
"url":"http:\/\/www.costco.ca",
"specials":{
"count":0,
"items":[
]
},
"hereNow":{
"count":0,
"groups":[
]
},
"referralId":"v-1366316196"
}
]
}
}
I made a class like this
public class Response
{
public string Meta { get; set; }
public List<Venue> Venues { get; set; }
}
public class Venue
{
public string Id { get; set; }
public string Name { get; set; }
public Contact Contact { get; set; }
public Location Location { get; set; }
public string CanonicalUrl { get; set; }
public Categories Categories { get; set; }
public bool Verified { get; set; }
}
var response = client.Execute<Response>(request);
var test = response.Data;
Yet Venues is always null. I am not sure why though.
You simply need to go a level deeper in the JSON response. One level up from the venues property is the response property, which is not currently represented in your Response class.
You have two ways to solve this.
1) Add another wrapping response object, which contains the missing response property
// this is the new wrapping object
public class FourSquareResponse
{
public string Meta { get; set; }
public VenueResponse Response { get; set; } // previously missing
}
public class VenueResponse
{
public List<Venue> Venues { get; set; }
}
public class Venue
{
public string Id { get; set; }
public string Name { get; set; }
public Contact Contact { get; set; }
public Location Location { get; set; }
public string CanonicalUrl { get; set; }
public Categories Categories { get; set; }
public bool Verified { get; set; }
}
And executing the request...
var request = new RestRequest(uri);
var response = client.Execute<Response>(request);
2) Ignore the meta property and start parsing at the response property.
*As an aside, it looks like the meta property of the JSON response might be an HTTP status code. If it is and you still need it, RestSharp provides that for you as well (see below).
public class Response
{
public string Meta { get; set; }
public List<Venue> Venues { get; set; }
}
public class Venue
{
public string Id { get; set; }
public string Name { get; set; }
public Contact Contact { get; set; }
public Location Location { get; set; }
public string CanonicalUrl { get; set; }
public Categories Categories { get; set; }
public bool Verified { get; set; }
}
However, this will require telling RestSharp where to start parsing the response.
var request = new RestRequest(uri)
{
RootElement = "response"
};
var response = client.Execute<Response>(request);
// and the HTTP status (if that's what you need)
response.StatusCode
If i am going in right direction then, ur JSON is not Valid
Error:Strings should be wrapped in double quotes
Get it validated jsonformatter
[UPDATED]
Valid JSON would be like:-
{
"meta": {
"code": 200
},
"notifications":
[
{
"type": "notificationTray",
"item": {
"unreadCount": 0
}
}
],
"response": {
"venues": [
{
"id": "4e15d1348877cd5712112a44",
"name": "The Arena",
"contact": { },
"location": {
"address": "110 Wall Street",
"lat": 40.70432634495503,
"lng": -74.0055421062419,
"distance": 671,
"city": "New York",
"state": "NY",
"country": "United States",
"cc": "US"
},
"canonicalUrl": "https://foursquare.com/v/the-arena/4e15d1348877cd5712112a44",
"categories": [
{
"id": "4bf58dd8d48988d1e4941735",
"name": "Campground",
"pluralName": "Campgrounds",
"shortName": "Campground",
"icon": {
"prefix": "https://foursquare.com/img/categories_v2/parks_outdoors/campground_",
"suffix": ".png"
},
"primary": true
}
],
"verified": false,
"stats": {
"checkinsCount": 149,
"usersCount": 25,
"tipCount": 4
},
"specials": {
"count": 0,
"items": [ ]
},
"hereNow": {
"count": 0,
"groups": [ ]
},
"referralId": "v-1366314443"
}
]
}
}
JSON deserialization to .NET objects is case sensative. Your property names don't match the JSON tags properly, and that is why when you attempt to deserialize, you are getting back NULL.