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;}
}
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 was wondering how I could at best deserialize this json string. For doing that I am using Newtonsoft.json as a plugin with Xamarin.
I only need the parts that says "transaction" and the array in it "transactions" in a list.
{
"id": 999,
"transactions": [
{
"order": 1,
"displayName": "01_lgn",
"transaction": {
"id": 7791,
"name": "01_lgn",
"description": null,
"warning": 1,
"poor": 2,
"timeOut": 45,
"tolerated": 3,
"frustrated": 7,
"state": 1,
"includeInThroughputCalculation": true
}
}
{
"order": 2,
"displayName": "02",
"transaction": {
"id": 7793,
"name": "02",
"description": null,
"warning": 1,
"poor": 2,
"timeOut": 45,
"tolerated": 3,
"frustrated": 7,
"state": 1,
"includeInThroughputCalculation": true
}
}
],
"defies": null,
"state": 1,
"reportDisplayName": "testSomething"
}
What I already have tried is to put it in a strongly typed class and then make a list of it.
public class testTransaction
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("state")]
public int State { get; set; }
[JsonProperty("reportDisplayName")]
public string ReportDisplayName { get; set; }
[JsonProperty("transactions")]
public List<testTransactions> testTransactions { get; set; }
}
public class testTransactions
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description")]
public object Description { get; set; }
[JsonProperty("warning")]
public int Warning { get; set; }
[JsonProperty("poor")]
public int Poor { get; set; }
[JsonProperty("timeOut")]
public int TimeOut { get; set; }
[JsonProperty("tolerated")]
public int Tolerated { get; set; }
[JsonProperty("frustrated")]
public int Frustrated { get; set; }
[JsonProperty("state")]
public int State { get; set; }
[JsonProperty("includeInThroughputCalculation")]
public bool IncludeInThroughputCalculation { get; set; }
}
But when I try to deserialize it in this way the "searchResult" is empty and I see that nothing is added to the list.
var bleh = jsonstring;
JObject parsedketenObject = JObject.Parse(bleh);
IList<JToken> jTokenResults1 = parsedketenObject;
IList<JToken> jTokenResults2 = parsedketenObject ["transactions"].Children ().ToList ();
IList<JToken> jTokenResults3 = parsedketenObject["transactions"][0]["transaction"].Children().ToList();
_Transactions_list = new List<testTransaction>();
foreach (JToken result in jTokenResults2)
{
testTransaction searchResult = JsonConvert.DeserializeObject<testTransaction>(result.ToString());
_Transactions_list.Add(searchResult);
}
Firstly, the JSON seems to be malformed, you are missing comma.
{
"id": 999,
"transactions": [
{
"order": 1,
"displayName": "01_lgn",
"transaction": {
"id": 7791,
"name": "01_lgn",
"description": null,
"warning": 1,
"poor": 2,
"timeOut": 45,
"tolerated": 3,
"frustrated": 7,
"state": 1,
"includeInThroughputCalculation": true
}
}, <-------- HERE
{
"order": 2,
"displayName": "02",
"transaction": {
"id": 7793,
"name": "02",
"description": null,
"warning": 1,
"poor": 2,
"timeOut": 45,
"tolerated": 3,
"frustrated": 7,
"state": 1,
"includeInThroughputCalculation": true
}
}
],
"defies": null,
"state": 1,
"reportDisplayName": "testSomething"
}
Additionally, try these for your POCO instead:
public class TransactionDetails
{
public int id { get; set; }
public string name { get; set; }
public object description { get; set; }
public int warning { get; set; }
public int poor { get; set; }
public int timeOut { get; set; }
public int tolerated { get; set; }
public int frustrated { get; set; }
public int state { get; set; }
public bool includeInThroughputCalculation { get; set; }
}
public class Transaction
{
public int order { get; set; }
public string displayName { get; set; }
public TransactionDetails transaction { get; set; }
}
public class RootObject
{
public int id { get; set; }
public List<Transaction> transactions { get; set; }
public object defies { get; set; }
public int state { get; set; }
public string reportDisplayName { get; set; }
}
Then you can use
var x = JsonConvert.DeserializeObject<RootObject>(blah);
x will contain transactions, which is already a list.
This method is not strongly typed, but it will work:
var jsonString = GetTheJson(); // however you get your json
dynamic jsonObject = JsonConvert.DeserializeObject(jsonString);
foreach (var txn in jsonObject.transactions)
{
Console.WriteLine("{0} {1} {2}", txn.order, txn.displayName, txn.transaction.id);
}
The best way to serialize/deserialize a json string to json object is using Google Gson library. You should create DTO files and use its type to serialize the string.
The documentation can be found here: https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/Gson.html
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.