I am getting null for no reason in my API. Why is this?
[AllowAnonymous]
[HttpPost("category")]
public async Task<IActionResult> PostProductCategory([FromBody] ProductCategoryViewModel message)
model:
public class ProductCategoryViewModel
{
public int? Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Advantages { get; set; }
public decimal? Liambda { get; set; }
public string Icon { get; set; }
public string UseCase { get; set; }
public string UseCaseTwo { get; set; }
public int? PackageType { get; set; }
}
json that i send :
{
advantages: "",
description: "",
icon: "",
id: 0,
liambda: "1111",
name: "asdfas",
packageType: 1,
useCase: "",
useCaseTwo: ""
}
Ok fixed the problem. It was quoted, I just copied from other place. the problem was when I enter data in JS I used input field "text" for decimal? value. and that is why it was not working.
Related
I've got a WPF / .Net Core 3.0 app which is consuming a Web API.
It executes a GET on an API endpoint and then tries to deserialize the JSON.
However, it's giving an error when trying to deserialize the DateTime fields.
Here's the code:
private HttpClient httpClient = new HttpClient();
private async Task GetClients()
{
var serializer = new DataContractJsonSerializer(typeof(List<ClientGetDto>));
var streamTask = httpClient.GetStreamAsync("https://mywebapp.com/api/Clients");
List<ClientGetDto> clientDtos = serializer.ReadObject(await streamTask) as List<ClientGetDto>;
}
The ClientGetDto model looks like this:
{
public int Id { get; set; }
public string ClientCode { get; set; }
public string ApiUrl { get; set; }
public string CompanyName { get; set; }
public string FranchiseName { get; set; }
public int? ProLicenses { get; set; }
public int? LiteLicenses { get; set; }
public int? ProSalesLicenses { get; set; }
public int? LiteSalesLicenses { get; set; }
public bool? IsActive { get; set; }
public DateTime? StartOfAgreementDate { get; set; }
public int? DebitOrderDay { get; set; }
public DateTime? DebitOrderStartDate { get; set; }
public decimal? ContractAmount { get; set; }
public bool? DebitOrderFormReceived { get; set; }
public bool? CancellationReceived { get; set; }
public DateTime? CancellationDate { get; set; }
public string CompanyRegNo { get; set; }
public string DbUrl { get; set; }
public string DbName { get; set; }
public double? CloudStorageQuota { get; set; }
public string Comments { get; set; }
public int? FranchiseId { get; set; }
public bool? IsTestDb { get; set; }
public bool? IsGumtreeRegistered { get; set; }
public int? FusionClientId { get; set; }
public string CountryCode { get; set; }
}
and the JSON that is returned by the API is:
[
{
"id": 3,
"clientCode": "cx0007",
"apiUrl": "https://mywebapp/api",
"companyName": "ACME Company",
"franchiseName": "ACME Franchise",
"proLicenses": 1,
"liteLicenses": 0,
"proSalesLicenses": 0,
"liteSalesLicenses": 0,
"isActive": true,
"startOfAgreementDate": "2007-08-01T00:00:00",
"debitOrderDay": 1,
"debitOrderStartDate": "2012-03-01T00:00:00",
"contractAmount": 695.00,
"debitOrderFormReceived": true,
"cancellationReceived": false,
"cancellationDate": "2012-10-18T00:00:00",
"companyRegNo": "",
"dbUrl": "mydb.co.za",
"dbName": "db1",
"cloudStorageQuota": 5.0,
"comments": null,
"franchiseId": null,
"isTestDb": false,
"isGumtreeRegistered": false,
"fusionClientId": null,
"countryCode": "US"
},
...
]
The error I'm getting is:
"There was an error deserializing the object of type
System.Collections.Generic.List`1[[PropWorxManager.DTOs.ClientGetDto,
PropWorxManager, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null]].
DateTime content '2007-08-01T00:00:00' does not
start with '\/Date(' and end with ')\/' as required for
JSON."} System.Runtime.Serialization.SerializationException
After some research I tried this:
var settings = new DataContractJsonSerializerSettings
{
DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("o")
};
var serializer = new DataContractJsonSerializer(typeof(List<ClientGetDto>), settings);
But that then gives this error:
"There was an error deserializing the object of type
System.Collections.Generic.List`1[[PropWorxManager.DTOs.ClientGetDto,
PropWorxManager, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null]].
String '2007-08-01T00:00:00' was not recognized
as a valid
DateTime."} System.Runtime.Serialization.SerializationException
Any suggestions would be welcome. Thank you.
P.S. The API is also written in .Net Core 3.0 if that helps...
This worked:
var settings = new DataContractJsonSerializerSettings
{
DateTimeFormat = new System.Runtime.Serialization.DateTimeFormat("o")
};
var serializer = new DataContractJsonSerializer(typeof(List<ClientGetDto>), settings);
I've got a simple WPF / .Net Core 3.0 app which executes a GET on a Web API endpoint:
private HttpClient httpClient = new HttpClient();
private async Task GetClients()
{
var serializer = new DataContractJsonSerializer(typeof(List<ClientGetDto>));
var streamTask = httpClient.GetStreamAsync("https://mywebapp.com/api/Clients");
List<ClientGetDto> clientDtos = serializer.ReadObject(await streamTask) as List<ClientGetDto>;
}
ClientGetDto looks like this:
{
public int Id { get; set; }
public string ClientCode { get; set; }
public string ApiUrl { get; set; }
public string CompanyName { get; set; }
public string FranchiseName { get; set; }
public int? ProLicenses { get; set; }
public int? LiteLicenses { get; set; }
public int? ProSalesLicenses { get; set; }
public int? LiteSalesLicenses { get; set; }
public bool? IsActive { get; set; }
public DateTime? StartOfAgreementDate { get; set; }
public int? DebitOrderDay { get; set; }
public DateTime? DebitOrderStartDate { get; set; }
public decimal? ContractAmount { get; set; }
public bool? DebitOrderFormReceived { get; set; }
public bool? CancellationReceived { get; set; }
public DateTime? CancellationDate { get; set; }
public string CompanyRegNo { get; set; }
public string DbUrl { get; set; }
public string DbName { get; set; }
public double? CloudStorageQuota { get; set; }
public string Comments { get; set; }
public int? FranchiseId { get; set; }
public bool? IsTestDb { get; set; }
public bool? IsGumtreeRegistered { get; set; }
public int? FusionClientId { get; set; }
public string CountryCode { get; set; }
}
and the JSON that is returned by the API is:
[
{
"id": 3,
"clientCode": "cx0007",
"apiUrl": "https://mywebapp/api",
"companyName": "ACME Company",
"franchiseName": "ACME Franchise",
"proLicenses": 1,
"liteLicenses": 0,
"proSalesLicenses": 0,
"liteSalesLicenses": 0,
"isActive": true,
"startOfAgreementDate": "2007-08-01T00:00:00",
"debitOrderDay": 1,
"debitOrderStartDate": "2012-03-01T00:00:00",
"contractAmount": 695.00,
"debitOrderFormReceived": true,
"cancellationReceived": false,
"cancellationDate": "2012-10-18T00:00:00",
"companyRegNo": "",
"dbUrl": "mydb.co.za",
"dbName": "db1",
"cloudStorageQuota": 5.0,
"comments": null,
"franchiseId": null,
"isTestDb": false,
"isGumtreeRegistered": false,
"fusionClientId": null,
"countryCode": "US"
},
...
]
My problem is that the code is correctly deserializing the JSON into a List of ClientGetDto objects, but all the fields are null. It's not throwing any exceptions or anything. I've tried decorating my ClientGetDto model with [DataContract] and [DataMember] but it's made no difference (nor would it, since the names of the fields of the model are exactly the same as those in the JSON data)
Any ideas?
You should mark each property with [JsonPropertyName("")] because json is case sensitive (I think).
I have been having a hard time trying to figure this out that I've just about torn out all my hair now.
Using this section of code (Added a var result that I looking at with a stoppoint):
public async Task<string> GetHttpSPContentWithToken(string url, string token)
{
var httpClient = new System.Net.Http.HttpClient();
System.Net.Http.HttpResponseMessage response;
try
{
var request = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Get, url);
//Add the token in Authorization header
request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
response = await httpClient.SendAsync(request);
var content = await response.Content.ReadAsStringAsync();
var result = JsonConvert.DeserializeObject<SharePointListItems.Fields>(content);
return content;
}
catch (Exception ex)
{
return ex.ToString();
}
}
The content that I receive is this (updated getting rid of extra information):
{
"#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('root')/lists('FBA0AB63-8453-4BB9-AA17-142A5D72A50D')/items/$entity",
"#odata.etag": "\"60d40002-0f08-4f29-afa7-0287137b863b,1\"",
"createdDateTime": "2018-08-07T14:28:47Z",
"eTag": "\"60d40002-0f08-4f29-afa7-0287137b863b,1\"",
"id": "1",
"lastModifiedDateTime": "2018-08-07T14:28:47Z",
"webUrl": "https://XXXX.sharepoint.com/Lists/TestList/1_.000",
"createdBy": {
"user": {
"email": "XXXX#XXXX.onmicrosoft.com",
"id": "b5f81cc6-f8b7-46b7-8e10-6ce1b9689c23",
"displayName": "TK"
}
},
"lastModifiedBy": {
"user": {
"email": "XXXX#XXXX.onmicrosoft.com",
"id": "b5f81cc6-f8b7-46b7-8e10-6ce1b9689c23",
"displayName": "TK"
}
},
"parentReference": {},
"contentType": {
"id": "0x010001403BD420356E4ABE3B63E5AEC0713D"
},
"fields#odata.context": "https://graph.microsoft.com/v1.0/$metadata#sites('root')/lists('FBA0AB63-8453-4BB9-AA17-142A5D72A50D')/items('1')/fields/$entity",
"fields": {
"#odata.etag": "\"60d40002-0f08-4f29-afa7-0287137b863b,1\"",
"Title": "1",
"UserName": "TK",
"UserAge": "47",
"UserTitle": "Developer"
}
}
I just want the values forUserAge, UserName, and UserTitle to put each into a textbox, but not sure how to pull them out.
I am pretty sure that I need to set up a class of some sort, but it is the #odata parts that are breaking my back.
Everything that I have tried just gives me back a null value. I see the value there, just not sure how to parse/pull it out.
I have looked at this (updated):
using Newtonsoft.Json;
using System;
public class SharePointListItems
{
public class UserCreated
{
public string email { get; set; }
public string id { get; set; }
public string displayName { get; set; }
}
public class CreatedBy
{
public UserCreated user { get; set; }
}
public class UserModified
{
public string email { get; set; }
public string id { get; set; }
public string displayName { get; set; }
}
public class LastModifiedBy
{
public UserModified user { get; set; }
}
public class ParentReference
{
}
public class ContentType
{
public string id { get; set; }
}
public class Fields
{
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
public string Title { get; set; }
public string UserName { get; set; }
public string UserAge { get; set; }
public string UserTitle { get; set; }
}
public class RootObject
{
[JsonProperty("#odata.context")]
public string ODataContext { get; set; }
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
public DateTime createdDateTime { get; set; }
public string eTag { get; set; }
public string id { get; set; }
public DateTime lastModifiedDateTime { get; set; }
public string webUrl { get; set; }
public CreatedBy createdBy { get; set; }
public LastModifiedBy lastModifiedBy { get; set; }
public ParentReference parentReference { get; set; }
public ContentType contentType { get; set; }
[JsonProperty("fields#odata.context")]
public string FieldsODataContext { get; set; }
public Fields fields { get; set; }
}
}
But then I run into the issue that there is two [JsonProperty("#odata.etag")].
The [JsonProperty] custom attribute is added to the C# property that actually holds that value. Instead of putting the attribute on the Title or createDateTime property, you need to put them on their own properties:
public class RootObject
{
[JsonProperty("#odata.context")]
public string ODataContext { get; set; }
[JsonProperty("#odata.etag")]
public string ODataETag { get; set; }
// No attribute needed here
public DateTime createdDateTime { get; set; }
// etc...
Also, you are trying to parse the content as a Fields class, but it is a RootObject; you need to use
JsonConvert.DeserializeObject<SharePointListItems.RootObject>(content)
To get the object.
I have been looking for ages and found some similar questions but no answers which fixed my issue.
I have recently developed a Web API project with seperate server side and client side code. I am wanting to do some testing through apiary, mainly for posting data. This requires me to have a "sample" of the posted JSON. However i cannot seem to get a working sample (I am using Postman to test the JSON).
I am sending a ViewModel:
public class ExampleViewModel
{
public ExampleModel exampleModel { get; set; }
public String[] strings { get; set; }
}
With the model:
public class ExampleModel
{
public long ID { get; set; }
public string User { get; set; }
public string Title { get; set; }
public string Type { get; set; }
public string Description { get; set; }
public bool Recieved { get; set; }
public bool CompleteRemotly { get; set; }
public bool CompleteInField { get; set; }
public string Email { get; set; }
public Nullable<DateTime> RecievedDate { get; set; }
public Nullable<DateTime> ScheduledFor { get; set; }
public Nullable<DateTime> CompleteOn { get; set; }
public string Priority { get; set; }
public string DiagnosticReports { get; set; }
public string CReference { get; set; }
public string JReference { get; set; }
}
The format the POST is expecting is:
Key: "evm",
Value: {APIProject.ViewModels.ExampleViewModel}
And:
APIProject.ViewModels.ExampleViewModel:
{
strings = [""],
exampleModel = {ExampleModel}
}
My latest attempt is:
{
"evm":{
"ExampleViewModel":{
"exampleModel":{
"ID":0,
"User":"Harrison",
"Title":"Other",
"Type":"Other",
"Description":"ygfvgufuf",
"Recieved":true,
"CompleteRemotly":false,
"CompleteInField":false,
"Email":null,
"RecievedDate":"\/Date(1458133155546)\/",
"ScheduledFor":null,
"CompleteOn":null,
"Priority":"Low",
"DiagnosticReports":null,
"CPA_Reference":null,
"Jira_Reference":null,
"strings":[]
},
"strings":[""]
}
}
}
Which returns:
Key: "evm",
Value: {APIProject.ViewModels.ExampleViewModel}
And:
APIProject.ViewModels.ExampleViewModel:
{
strings = null,
exampleModel = null
}
So i got this to work by sending the following JSON, I guess i was over complicating the situation.
{
"requestManagements":{
"RequestID":0,
"User":"Harrison",
"RequestTitle":"Other",
"RequestType":"Other",
"RequestDescription":"ygfvgufuf",
"RequestRecieved":true,
"RequestCompleteRemotly":false,
"RequestCompleteInField":false,
"Email":null,
"RequestRecievedDate":"\/Date(1458133155546)\/",
"ScheduledFor":null,
"CompleteOn":null,
"Priority":"Low",
"DiagnosticReports":null,
"CPA_Reference":null,
"Jira_Reference":null,
"RequestManagerImages":[]
},
"images":[""]
}
I want to parse a json to List how can we do that. I have tried the following code but it didnt worked
Dictionary<string, object> pGateways=(Dictionary<string,object>)Json.JsonParser.FromJson(jsonString);
List<object> creditOptions = new List<object>();
creditOptions = (List<object>)pGateways;
And after getting it int list i want to loop through it
Here is my sample json
{
"MessageCode": "CS2009",
"Status": "Y",
"ErrorCode": "0",
"ErrorDescription": "Success",
"account":
{
"card":
[
{
"cardend": "asd",
"token": "aads",
"cardstart": "asdad",
"accounttype": "asda",
"cardnetwork": "as",
"issuer": "asd",
"customername": "a",
"expdate": "04/2018"
},
{
"cardend": "asda",
"token":"adssadsa",
"cardstart": "asd",
"accounttype": "asd",
"cardnetwork": "asd",
"issuer": "asda",
"customername": "asd",
"expdate": "03/2016"
}
],
"bank": []
}
}
The best option could be to use the JsonConvert in order to parse Json into a List.
Reference: JSON Parsing in Windows Phone
You can use Json.Net.
To install Json.NET use NugetGallery : Json.net Nugets Gallery
And you can use json2Csharp.com for generate c# classes from json
The JSON string you posted is not suitable for straight-forward deserialization to List. The easiest thing to do is use the online JSON 2 CSharp tool to generate classes and deserialize the json string to it. Here is an example of the generated classes:
public class Card
{
public string cardend { get; set; }
public string token { get; set; }
public string cardstart { get; set; }
public string accounttype { get; set; }
public string cardnetwork { get; set; }
public string issuer { get; set; }
public string customername { get; set; }
public string expdate { get; set; }
}
public class Account
{
public List<Card> card { get; set; }
public List<object> bank { get; set; }
}
public class RootObject
{
public string MessageCode { get; set; }
public string Status { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
public Account account { get; set; }
}
And here is the logic for deserialization:
var root = JsonConvert.DeserializeObject<RootObject>(jsonStr);
where the jsonStr variable holds the json string you posted.
You need to use json2csharp tool to generate classes and deserialize the JSON string to list.
Here is the Classes generated from your JSON string.
public class Card
{
public string cardend { get; set; }
public string token { get; set; }
public string cardstart { get; set; }
public string accounttype { get; set; }
public string cardnetwork { get; set; }
public string issuer { get; set; }
public string customername { get; set; }
public string expdate { get; set; }
}
public class Account
{
public List<Card> card { get; set; }
public List<object> bank { get; set; }
}
public class RootObject
{
public string MessageCode { get; set; }
public string Status { get; set; }
public string ErrorCode { get; set; }
public string ErrorDescription { get; set; }
public Account account { get; set; }
}
and Deserialize your JSON object using JsonConvert,
Suppose e.result is your JSON string then
var rootObject = JsonConvert.DeserializeObject<RootObject>(e.Result);
foreach (var blog in rootObject.Card)
{
//access your data like this- `blog.cardend;` or `blog.token;`
}