Per resource Json Formatting asp.net core - c#

I am building a REST api using ASP.Net core 1.0.0, and I am currently trying to figure out a way to serialize and deserialize Incoming request body and out going responses.
for example, I have the following
[HttpPost]
public async Task<IActionResult> Post([FromBody]ScheduleEvent scheduleEvent)
{
.
.
.
return Ok(scheduleEvent);
}
The thing is, ScheduleEvent is a database model, so not all the properties should be sent or received from/to the client.
The only solutions I could find are either creating DTO classes and converting the DTO objects to and from model objects, or placing jsonattributes over the object. The first seems like an unnecessary workaround, and the second forces you to make your models depend on json.net, besides the fact that it also makes serialization and deserialization exactly the same. Basicly they all seem like bad solutions - mostly since json.net allows using schemas to invalidate incoming/outgoing json, and If someone were to use it he could create such functionality easily by creating input and output schemas per type or per Controller/Action.
However, JsonConverter doesn't seem like the right way to go, and creating my own json output and input formatters seems like a lot of work, for something that might have a better solution.
So basically, the question is, what is the common way of addressing this problem, and do you know any better solution?

Related

How to deserialize LogEvents from Serilog stored in CouchDB

I'm currently logging (Logging application) to a CouchDB database with Serilog, and with a handful of Types being decomposed into the database.
I've got a separate application (Reporting application) that is trying to pull LogEvents out of the database and deserialize them into the original LogEvents. The Reporting application is just as aware of the same types as the logging application and the specific Types in the database are fully decomposed into it.
Json.Net's deserializer has problems with deserializing the MessageTemplate. Even with a custom converter, it has so many problems that I'm probably doing it wrong (various exceptions deserializing, but no real pattern that I can tell).
Has anyone been able to do this successfully? I was under the impression that being able to pull Types out of the logs is one of the features of Serilog, and all the data is there, so I don't see why it's not possible.
These Types are all fully serializable as well, they're regularly serialized/deserialized by Json.net.
After more research, I've found a way to partially solve the problem. Generate new classes with http://json2csharp.com/ - rename the RootObject to something (e.g., SpecificLogEvent) and use:
var logEvent = JsonConvert.DeserializeObject<SpecificLogEvent>(doc.Value);
Then convert the objects to the real objects where needed.
I'll not mark this as the answer for awhile, because I'd love an easy back and forth and avoid this extra step which creates redundant classes.

How to walk a C# object hierarchy and create JSON string?

I am creating a metadata site for our API. It is like swagger implementation. Currently I am facing difficulty with creating a sample JSON representation of our request response objects. These are complex objects that may even contain lists.
Right now I am at the point where via using reflection I am able to find all the request and their corresponding response objects.
Is there a library that can convert a reflection
assembly.GetType("FullyQuallifiedObjectName")
output to a JSON sample string? My research so far has not been fruitful.
Implementing your own inspector class may be too difficult and take much time. You may consider Microsoft's way to build help pages in WebApi. New Mvc4 and Mvc5 projects in VS2013 already contain complete help pages in WebApi templates.
(You do not need to implement custom XmlDocumentationProvider, just create a new WebApi project in VisualStudio 2013 and you will find completed xml doc provider)
If you use WebApi - it's exactly what you need. If not - modify and reuse already implemented xml doc provider.

NSJSONSerialization in iOS 5 like c# serialize to class

I am porting our C# MVC Repository code to iOS5 for the iPad. I have been working successfully with the calls to the services, pulling Json and serializing to built in NS objects. But this seems like a lot of work to pull the pieces out and then assign them to a class. In C# this is a breeze, just serialize to your class, mapped to the data attributes and you are off with a strong typed view model.
Anyone done something similar in iOS/XCode and I know you can use NSData in interesting ways, I am just not expert enough yet and I am looking for pointers and best practces.
You question is not very clear to me. But as per my interpretation, you want to consume web service data in your application.In that case, see if it helps to you:
Are you able to connect to web service and get serialised data from it? You will receive data in object of type NSData. Then you you can use NSXMLParser class (initialised with NSData received from web service) and it's delegate methods to parse the data.
This blog may help you:
http://iphonebyradix.blogspot.com/2011/04/working-with-webservices.html
If you want to write serialised data, using NSJSONSerialization class then you can use
+ (id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error
method. You can find details on developer.apple :
https://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
Try the KeyValueObjectMapping project on github, it has some good support for object mapping(auto) and remapping if the property/class is named different from the context of the json.

Best way to parse JSON string without getting stuck with structure or class

Could you help me to find out the best way to parse JSON string (coming as web service parameter).
using either JavaScriptSerializer or DataContractJsonSerializer based on deserialization is useless for me since the client does't accept to share with me common data structure (class).
Regards
I've used JSON.NET various times in the past - it lets you parse JSON into something a bit like an XML DOM, rather than requiring "real" types. Look at the "LINQ to JSON" part of the documentation.

Confused about how to use JSON in C#

The answer to just about every single question about using C# with JSON seems to be "use JSON.NET", but that's not the answer I'm looking for.
The reason I say that is, from everything I've been able to read in the documentation, JSON.NET is basically just a better performing version of the DataContractSerializer built into the .NET framework...
Which means if I want to deserialize a JSON string, I have to define the full, strongly-typed class for EVERY request I might have. So if I have a need to get categories, posts, authors, tags, etc., I have to define a new class for every one of these things.
This is fine if I built the client and know exactly what the fields are, but I'm using someone else's API, so I have no idea what the contract is unless I download a sample response string and create the class manually from the JSON string.
Is that the only way it's done? Is there not a way to have it create a kind of hashtable that can be read with json["propertyname"]?
Finally, if I do have to build the classes myself, what happens when the API changes and they don't tell me (as twitter seems to be notorious for doing)? I'm guessing my entire project will break until I go in and update the object properties...
So what exactly is the general workflow when working with JSON? And by general I mean library-agnostic. I want to know how it's done in general, not specifically to a target library...
It is very hard to be library-agnostic as you request because how you work with json really depends on the library you use. As an example inside JSON.NET there are multiple ways you could work with JSON. There is the method you talk about with direct serialization into objects. That is type safe but will break if the data from your API changes. However, there is also a LINQ-to-JSON that provides a JObject (which behaves fairly similarly to XElement) that provides a way to do JObject["key"] as you requested in your question. If you are really just looking for a flexible way to work with JSON inside C#, then check out JSON.NET's LINQ-to-JSON.
In reality no matter how you do it, if the API changes your code is likely to break. Even if you are just strictly a hashtable-based approach, your code will still be likely to break if the data coming back changes.
Edit
JSON.NET Documentation
Examples
If you check out the examples, the second one should give you a good example of how LINQ-to-JSON works. It allows you to work with it without defining any classes. Everything gets converted to standard framework classes (mostly collections and strings). This avoids the need to maintain classes.
I've been a Perl developer for over a decade, and I've just recently started to work in C#. I'm surprised by how much I like it (I don't like Java at all) but one of the most difficult cognitive switches is going from "Everything can be treated as a string and the language takes care of conversions" to "Pre-define your types." In this case string-thinking might be an advantage, because it's what you need to do for the kind of API you're asking for.
You need to write a JSON parser that understands the syntax, which is fairly simple: comma-separated lists, key/value pairs, {} for hashes/objects, [] for arrays, and quoting/escaping constructs. You'll want to create a Hashtable to start because the top-level entity in JSON is always an object, then scan the JSON string character-by-character. Pull out key/value pairs; if the value starts with { then add it as a new Hashtable, if it starts with [ add it as a new ArrayList, otherwise add it as a string. If you get { or [ you'll need to recursively descend to add the child data elements.
If .NET has a good recursive descent parser, you could probably use that to make the job simpler or more robust, but JSON is simple enough to make this a good and reasonably completable exercise.

Categories

Resources