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
Related
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;}
}
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; }
}
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; }
}
here is my json response that I am trying to deserialize
[{
"Musician": {
"id": "554343",
"Name": "16408",
"Age": "22"
},
"Albums": [{
"id": "34343",
"AlbumName": "Super charge",
"ReleaseDate": "",
"Hits": ""
}, {
"id": "34222",
"AlbumName": "Super 2",
"ReleaseDate": "",
"Hits": ""
}]
},
{
"Musician": {
"id": "554344",
"Name": "16468",
"Age": "32"
},
"Albums": [{
"id": "34323",
"AlbumName": "Awesome one",
"ReleaseDate": "",
"Hits": ""
}, {
"id": "34222",
"AlbumName": "Awesome two",
"ReleaseDate": "",
"Hits": ""
}]
}]
here are my class
public class Musician
{
public string id { get; set; }
public string Name { get; set; }
public string Age { get; set; }
}
public class Album
{
public string id { get; set; }
public string AlbumName { get; set; }
public string ReleaseDate { get; set; }
public string Hits { get; set; }
}
public class RootObject
{
public Musician Musician { get; set; }
public List<Album> Albums { get; set; }
}
this is the code i am using to deserialize objects
var musicians = JsonConvert.DeserializeObject<List<Musician>>(data);
var album = JsonConvert.DeserializeObject<List<Album>>(data);
musicians variable shows 2 counts of record while debugging but value of elements id,Name,Age always shows null. Not able to recognize what exactly causing it.
You should be deserializing as collection of RootObjects.
var musicians = JsonConvert.DeserializeObject<IEnumerable<RootObject>>(data);
Output