I have some JSON that i am sending over to my C# API and it looks like the following
{
"currency": "BTC",
"amount": "0.00049659",
"type": "bankToExchange"
}
The issue is when the model arrives in my controller, the type property is changed to #type which is making the post request fail.
The API I am trying to connect to uses type, so this cannot be changed. The post works in Postman, so is there a work around for this?
Add the DataMember name property on your type using JsonProperty:
[DataMember(Name = "#type")] //if not using NewtonSoft
[JsonProperty("#type")] //if using NewtonSoft
public string type { get; set; }
Use Data member attribute with property name. You can use by creating class for your json, as follows
[DataContract]
public class Sample{
[DataMember(Name = "#type")]
public string Type{get;set;}
}
You can try with another approach as well, which is elegant and more meaning full if you add comment for appending # before property name :
public class Sample{
public string #type{get;set;}
}
For reference: object to deserialize has a C# keyword
Related
I am trying to retrieve JSON data from an API, but one of the property names comes as #data.context . It is not a nested property. I've tested it with ExpandoObject as well, it is exactly like that. Normally in C # I would make a data model like
public class Data
{
public string #odata.context { get ; set; }
}
But this doesn't work, as C# doesn't let me have a comma in the variable name, nor have quotes around it. The # sign is already there
The JSON is as follows: this property that contains a link and then another one that contains a list of objects.
{
"#odata.context": "some link here",
"list" [ {}, {}
]
}
The list of objects do not give me any trouble, only the first property.
You can use JsonPropertyName attribute to map the json to the property e.g:
[JsonPropertyName("#odata.context")]
public string DataContext { get ; set; }
Microsoft docs
You might be consuming a poorly designed API. There are API specifications that tells how to structure and name JSON keys.
One way you can accomplish is
1 Fetch JSON response from API
2 Replace "#data.context" with "Context" or something similar in JSON string
3 Create class with property
public class Data
{
public string Context { get ; set; }
}
4 Deserialise it
How to post a dynamic JSON property to a C# ASP.Net Core Web API using MongoDB?
It seems like one of the advantages of MongoDB is being able to store anything you need to in an Object type property but it doesn't seem clear how you can get the dynamic property info from the client ajax post through a C# Web API to MongoDB.
We want to allow an administrator to create an Event with Title and Start Date/Time but we also want to allow the user to add custom form fields using Reactive Forms for whatever they want such as t-shirt size or meal preference... Whatever the user may come up with in the future. Then when someone registers for the event, they post EventID and the custom fields to the Web API.
We can have an Event MongoDB collection with _id, event_id, reg_time, and form_fields where form_fields is an Object type where the dynamic data is stored.
So we want to POST variations of this JSON with custom FormsFields:
Variation 1:
{
"EventId": "595106234fccfc5fc88c40c2",
"RegTime":"2017-07-21T22:00:00Z",
"FormFields": {
"FirstName": "John",
"LastName": "Public",
"TShirtSize": "XL"
}
}
Variation 2:
{
"EventId": "d34f46234fccfc5fc88c40c2",
"RegTime":"2017-07-21T22:00:00Z",
"FormFields": {
"Email": "John.Public#email.com",
"MealPref": "Vegan"
}
}
I would like to have an EventController with Post action that takes a custom C# EventReg object that maps to the JSON above.
EventController:
[HttpPost]
public void Post([FromBody]EventReg value)
{
eventService.AddEventRegistration(value);
}
EventReg Class:
public class EventReg
{
public EventReg()
{
FormFields = new BsonDocument();
}
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string EventRegId { get; set; }
[BsonElement("EventId")]
[BsonRepresentation(BsonType.ObjectId)]
public string EventId { get; set; }
[BsonElement("reg_time")]
public DateTime RegTime
{
set; get;
}
[BsonElement("form_fields")]
public MongoDB.Bson.BsonDocument FormFields { get; set; }
}
EventService
public string AddEventRegistration(EventReg eventReg)
{
this.database.GetCollection<EventReg>("event_regs").InsertOne(eventReg);
return eventReg.EventRegId;
}
Right now, if I post to the controller, my EventReg is null because it must not know how to map my JSON FormFields properties to a BsonDocument.
What type can I use for FormFields?
Can I have the FormFields property be a BsonDocument and is there an easy way to map the Web API parameter to that?
Is there an example of how some custom serializer might work in this case?
We could maybe use a dynamic type and loop through the posted properties but that seems ugly. I have also seen the JToken solution from a post here but that looks ugly also.
If MongoDB is meant to be used dynamically like this, shouldn't there be a clean solution to pass dynamic data to MongoDB? Any ideas out there?
In ASP.NET Core 3.0+ Newtonsoft.Json is not the default JSON serializer anymore. Therefore I would use JsonElement:
[HttpPost("general")]
public IActionResult Post([FromBody] JsonElement elem)
{
var title = elem.GetProperty("title").GetString();
...
The JToken example works to get data in but upon retrieval it causes browsers and Postman to throw an error and show a warning indicating that content was read as a Document but it was in application/json format. I saw the FormFields property being returned as {{"TShirtSize":"XL"}} so maybe double braces was a problem during serialization.
I ended up using the .NET ExpandoObject in the System.Dynamic namespace. ExpandoObject is compatible with the MongoDB BsonDocument so the serialization is done automatically like you would expect. So no need for weird code to manually handle the properties like the JToken example in the question.
I still believe that a more strongly typed C# representation should be used if at all possible but if you must allow any JSON content to be sent to MongoDB through a Web API with a custom C# class as input, then the ExpandoObject should do the trick.
See how the FormFields property of EventReg class below is now ExpandoObject and there is no code to manually handle the property of the object being saved to MongoDB.
Here is the original problematic and overly complex JToken code to manually populate an object with standard type properties and a dynamic FormFields property:
[HttpPost]
public void Post([FromBody]JToken token)
{
if (token != null)
{
EventReg eventReg = new EventReg();
if (token.Type == Newtonsoft.Json.Linq.JTokenType.Object)
{
eventReg.RegTime = DateTime.Now;
foreach (var pair in token as Newtonsoft.Json.Linq.JObject)
{
if (pair.Key == "EventID")
{
eventReg.EventId = pair.Value.ToString();
}
else if (pair.Key == "UserEmail")
{
eventReg.UserEmail = pair.Value.ToString();
}
else
{
eventReg.FormFields.Add(new BsonElement(pair.Key.ToString(), pair.Value.ToString()));
}
}
}
//Add Registration:
eventService.AddEventRegistration(eventReg);
}
}
Using ExpandoObject removes the need for all of this code. See the final code below. The Web API controller is now 1 line instead of 30 lines of code. This code now can insert and return the JSON from the Question above without issue.
EventController:
[HttpPost]
public void Post([FromBody]EventReg value)
{
eventService.AddEventRegistration(value);
}
EventReg Class:
public class EventReg
{
public EventReg()
{
FormFields = new ExpandoObject();
}
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string EventRegId { get; set; }
[BsonElement("event_id")]
[BsonRepresentation(BsonType.ObjectId)]
public string EventId { get; set; }
[BsonElement("user_email")]
public string UserEmail { get; set; }
[BsonElement("reg_time")]
public DateTime RegTime{ get; set; }
[BsonElement("form_fields")]
public ExpandoObject FormFields { get; set; }
}
EventService:
public string AddEventRegistration(EventReg eventReg)
{
this.database.GetCollection<EventReg>("event_regs").InsertOne(eventReg);
return eventReg.EventRegId;
}
If you are not sure about the type of Json you are sending i.e. if you are dealing with dynamic json. then the below approach will work.
Api:
[HttpPost]
[Route("demoPath")]
public void DemoReportData([FromBody] JObject Jsondata)
Http client call from .net core app:
using (var httpClient = new HttpClient())
{
return await httpClient.PostAsJsonAsync(serviceUrl,
new demoClass()
{
id= "demoid",
name= "demo name",
place= "demo place"
};).ConfigureAwait(false);
}
You can define FormFields as a string and send data to the API in string format after converting JSON to string:
"{\"FirstName\":"John\",\"LastName\":\"Public\",\"TShirtSize\":\"XL\"}"
Then in your controller parse the string to BsonDocument
BsonDocument.Parse(FormFields);
I would use AutoMapper to automate the conversion between the dto and the document
I'm new with Web API 2 / Entity Framework 6 project, I'm making REST services, but for one specific service I'm going to receive (via Post) a JSON before making any CRUD operations over any entity of the model, (have to make some business validations over the data, add or complement some things and decide on wich entity to save), the JSON is:
{
"head": {
"action": "create",
"object": "oneobject",
"user": "theuser"
},
"object": {
"name1": "a name 1",
"name2": "a name 2",
"description": "a description here"
},
"rule": [{
"name": "any name",
"value": "any value"
}, {
"name": "another name",
"value": "another value"
}]
}
So the json not maps directly to an entity, in fact I have no model or object for this. What would be the better way to work with it? I mean how to receive and parse the json. I'm new with web api and rest services, and I would appreciate you can help me and explain me with good details. Thanks guys.
Edit:
Any idea of the POCO or class that match this kind of json. ("rule" list It's variable, can be one or more).
After create this poco or class I would have to make a controller based on this?
As others have said, what you need is a POCO object to represent your request. Based on the information you have provided the following should achieve close enough to what you are after:
public enum CrudAction
{
Create,
Read,
Update,
Delete
}
public sealed class CrudRequestHeader
{
public CrudAction Action { get; set; }
public string Object { get; set; }
public string User { get; set; }
}
public sealed class RuleDefinition
{
public string Name { get; set; }
public string Value { get; set; }
}
public sealed class CrudRequest
{
public CrudRequestHeader Head { get; set;}
public Dictionary<string, string> Object { get; set; }
public List<RuleDefinition> Rule { get; set; }
}
In your Web API controller method you can then take a parameter of type CrudRequest and your JSON will be deserialized to this object, e.g:
public IHttpActionResult Post(CrudRequest crudRequest)
{
// TODO Implementation
}
You may notice I have used Dictionary<string, string> for CrudRequest.Object as it is variable how many key/values we will be supplied with, I have made the assumption that all values are strings, you can use an object value if you prefer but you will then need to handle the type of value. In the same principle I have used List<RuleDefinition> for CrudRequest.Rule to cater for the variable number of rules which may be supplied.
A LINQPad sample containing the above definitions and use with your input can be found here: http://share.linqpad.net/7rvmhh.linq
Although the JSON may not represent a logical entity in your model, you clearly have a mental model of the "shape" of the JSON data - I say this because you define it in your code snippet. You should create a POCO (plain old C# object) to represent this model, and deserialize the incoming JSON request to an object of that type. Once you've deserialized it to your object, it will be trivial to work with this data using object properties and such.
The best thing to do would be to create a class that models the object you expect back.
This way in your Web API method you can use the [FromBody] attribute to automatically parse the body of the request.
Example -
Your data contract would look like this:
public class MyContract
{
public string MyData { get; set;}
}
In your ApiController
[HttpPost]
[Route("api/myobject")]
public async Task ReceiveMyObject([FromBody]MyContract object) {
var data = object.MyData;
// Do whatever you need to do here.
}
This may seem tedious but this will let you keep your code organized.
Edit
So to create a contract out of this:
{
"head": {
"action": "create",
"object": "oneobject",
"user": "theuser"
},
"object": {
"name1": "a name 1",
"name2": "a name 2",
"description": "a description here"
},
"rule": [{
"name": "any name",
"value": "any value"
}, {
"name": "another name",
"value": "another value"
}]
}
You would do something like this:
public class MyContract
{
[JsonProperty("head")]
public MetaObject Head
{
get; set;
}
// Not sure if this will work, but it probably will
[JsonProperty("object")]
public JObject ExtendedInformation
{
get;
set;
}
[JsonProperty("rule")]
public Rule[] Rules
{
get;
set;
}
}
// "MetaObject" definition omitted but you can understand my point with the below
public class Rule
{
[JsonProperty("name")]
public string Name
{
get;
set;
}
[JsonProperty("value")]
public string Value
{
get;
set;
}
}
Usually a REST service issue a contract, which means some kind of metadata to describe the content of its messages, otherwise you cannot call this as a RESTful Web API. Take a look at this post from Roy Fielding, who created the term of REST API, if you want to know better what is REST and what is not.
So if your service is a true REST service you should be able to have a description somewhere that give you the possibility to parse the media.
However, if you still cannot find any way to understand how the JSON should be interpreted you may be able to use it inside a C# class anyway: take a look at the JObject class from Newtonsoft.Json that enables to use a dynamic object at runtime.
Basically, it is used like this:
using Newtonsoft.Json.Linq; // This needs the Newtonsoft.Json package
dynamic entity = JObject.Parse(jsonString);
string value = entity.key1;
string value2 = entity["key2"];
I did this simple demo with your data.
You can also check the full documentation of the class on the Newtonsoft website.
I'm using Restsharp to deserialize some webservice responses, however, the problem is that sometimes this webservices sends back a json response with a few more fields. I've manage to come around this so far by adding all possible field to my matching model, but this web service will keep adding/removing fields from its response.
Eg:
Json response that works:
{
"name": "Daniel",
"age": 25
}
Matching model:
public class Person
{
public string name { get; set; }
public int age { get; set; }
}
This works fine: Person person = deserializer.Deserialize<Person>(response);
Now suppose the json response was:
{
"name": "Daniel",
"age": 25,
"birthdate": "11/10/1988"
}
See the new field bithdate? Now everything goes wrong. Is there a way to tell to restsharp to ignore those fields that are not in the model?
If there's that much variation in the fields you're getting back, perhaps the best approach is to skip the static DTOs and deserialize to a dynamic. This gist provides an example of how to do this with RestSharp by creating a custom deserializer:
// ReSharper disable CheckNamespace
namespace RestSharp.Deserializers
// ReSharper restore CheckNamespace
{
public class DynamicJsonDeserializer : IDeserializer
{
public string RootElement { get; set; }
public string Namespace { get; set; }
public string DateFormat { get; set; }
public T Deserialize<T>(RestResponse response) where T : new()
{
return JsonConvert.DeserializeObject<dynamic>(response.Content);
}
}
}
Usage:
// Override default RestSharp JSON deserializer
client = new RestClient();
client.AddHandler("application/json", new DynamicJsonDeserializer());
var response = client.Execute<dynamic>(new RestRequest("http://dummy/users/42"));
// Data returned as dynamic object!
dynamic user = response.Data.User;
A simpler alternative is to use Flurl.Http (disclaimer: I'm the author), an HTTP client lib that deserializes to dynamic by default when generic arguments are not provided:
dynamic d = await "http://api.foo.com".GetJsonAsync();
In both cases, the actual deserialization is performed by Json.NET. With RestSharp you'll need to add the package to your project (though there's a good chance you have it already); Flurl.Http has a dependency on it.
I am using the Json.DeserializeObject method in windows phone, inorder to deserialize json, the problem I am having is one of the variable names, in the json has a space and I just can't get it to deserialize. it returns a null the whole time, and if I view the raw json it does contain a value
part of raw json:
\"Service Provider\":Test\"
When I try to generate a class for the json into which it needs to be deserialized, the Service Provider section tells me "Invalid Name" and that obviously doesn't work in C# as a variable name, but I believe the variable name can be anything:
public string __invalid_name__Service Provider { get; set; }
current code:
public string Service_Provider { get; set; }
Using Json.Net, Just decorate your property with "JsonProperty" Attribute
string json = #"{""Service Provider"":""Test""}";
var obj = JsonConvert.DeserializeObject<TempObject>(json);
public class TempObject
{
[JsonProperty("Service Provider")]
public string ServiceProvider;
}