List of objects in RavenDB - c#

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

Related

How to deserialize json inside a json to a string property

I am reading a json-string from an API (in a script component i SSIS). The json looks something like the one below (this is only one record, the real string contains many more). When trying to deserialize into a class containing the needed properties, I would like to put the "value" for the "costCenters"-property into a string property in my table. How ever, since the costCenters-value in itself contains a JSON, the deserialization fails (because it encounters the objects inside it).
If I exclude the property CostCenters from my class, it manages to deserialize the other properties just fine. I would think (hope) that it would be possible to force the inner JSON into a string property? Any suggestions?
This is my class that is used for the deserilazing:
internal class Unit
{
public int ParentId { get; set; }
public int CompanyId { get; set; }
public string Abbreviation { get; set; }
public string AbbreviationPath { get; set; }
public int Manager { get; set; }
public int UnitId { get; set; }
public string Name { get; set; }
public string LevelDescription { get; set; }
public int OrfuCompanyId { get; set; }
public string Resh { get; set; }
//If the below propery is commented out, the deserializing works fine.
public string CostCenters { get; set; }
public int Level { get; set; }
public int OrfuUnitId { get; set; }
}
This is how I call the deserializer for NewtonSoft:
var units = new List<Unit>();
units = JsonConvert.DeserializeObject<List<Unit>>(jsonString);
This is how the jsonString looks (edited):
[
{
"$id": "1",
"parentId": 999,
"companyId": 9123,
"abbreviation": "ZZZ",
"abbreviationPath": "SOMEPATH",
"costCenters": [
{
"$id": "12",
"costCenter": "12345",
"costCenterSourceId": "99",
"costCenterSource": "TBF",
"costCenterTypeId": "999",
"costCenterType": "TypeOfCostCenter",
"startDate": "2018-01-01T00:00:00",
"endDate": "9999-12-31T00:00:00"
},
{
"$id": "88",
"costCenter": "191945444",
"costCenterSourceId": "88",
"costCenterSource": "TBB",
"costCenterTypeId": "15",
"costCenterType": "SomeTextHere",
"startDate": null,
"endDate": null
}
],
"manager": 12345678,
"deputy": 0,
"homeShare": "\\\\someaddress.net\\someFolder\\SomeCode",
"objectGuid": "ThisIsAGUID",
"distinguishedName": "OU=ABC,OU=NNN,OU=FFF,OU=HHH,OU=HNV,OU=IDK,DC=heipaadeg,DC=com",
"orfuUnitId": 9125,
"orfuCompanyId": 9123,
"resh": "123456789",
"nis": "",
"unitId": 4321,
"name": "2 some name",
"level": 9,
"levelDescription": "Level number 4"
}
]
One workaround is to add a field to Unit called CostCentersString in which the CostCenters list is re-serialized:
In Unit class definition:
...
public List<dynamic> CostCenters { get; set; }
public String CostCentersString { get; set; }
Then use:
List<Unit> units = JsonConvert.DeserializeObject<List<Unit>>(jsonString);
foreach (Unit u in units)
{
u.CostCentersString = JsonConvert.SerializeObject(u.CostCenters);
}

Method to map data from two JSON Files

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

Post nested model

Currently my api post works like this:
POST: localhost:55974/api/trades/
{
"id": 1,
"baseProduct": {
"id": 1,
"productID": "sample string 2",
"tags": [
"sample string 1",
"sample string 2"
]
},
"productDescription": "sample string 2",
"images": [
"QEA=",
"QEA="
],
"price": 3,
"estimatedShippingDate": "2017-03-31T20:41:03.2760924+09:00"
}
What I want is to link the existing data with its id; something like this:
{
"id": 1,
"baseProduct": 1,
"productDescription": "sample string 2",
"images": [
"QEA=",
"QEA="
],
"price": 3,
"estimatedShippingDate": "2017-03-31T20:41:03.2760924+09:00"
}
Note that baseProduct has changed to its ID, but when I try to do this, I get this error:
{
"Message": "The request is invalid.",
"ModelState": {
"tradeModel.baseProduct": [
"Error converting value 3 to type 'EodiRoad.Models.BaseProductModel'. Path 'baseProduct', line 2, position 19."
]
}
}
This worked fine in django so I guess that it will have its way on ASP.NET too.
Any possible solutions?
=== EDIT ====
my data model looks like this.
Trademodel.cs
public class TradeModel
{
public int id { get; set; }
[Required]
[ForeignKey("baseProduct")]
public int baseProductId { get; set; }
public virtual BaseProductModel baseProduct { get; set; }
// public BaseProductModel baseProduct { get; set; }
public string productDescription { get; set; }
public List<byte[]> images { get; set; }
public int price { get; set; }
// Date infos
public DateTime estimatedShippingDate { get; set; }
}
BaseProductModel.cs
public class BaseProductModel
{
public int id { get; set; }
public string productID { get; set; }
// Not in use
public List<string> tags { get; set;}
}

Deserialize Json to C# object with array of arrays

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

What am I missing? RestSharp won't deserialize Json

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.

Categories

Resources