NSJSONSerialization in iOS 5 like c# serialize to class - c#

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.

Related

Per resource Json Formatting asp.net core

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?

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.

.cs class definitions auto-created in .ts

I need to have a REST server (written in C#) pass a JSON object to/from my typescript client running in a browser. The best way to do this is define the class on the C# side that then creates a JSON object passed to the client where that JSON object matches the class structure in the client.
Which leads to the obvious question - is there a way to define the classes in C# and then run some program that will create the .ts class definitions? Or the reverse where I write out the classes in .TS and a program then creates matching .cs classes?
What I want to avoid is having to make sure any member added on one side is then added exactly the same on the other side.
And in a perfect world, the comments written for the class members are carried across too.
Update: I know I can write such a tool. However I'm hoping it already exists as that's a lot of work.
Type lite http://type.litesolutions.net/ gets you halfway. Just the data member signature.
As you know json doesn't carry behaviour just data. So no functions will not be available on the other side. It's not a "transpiler"
And in a perfect world, the comments written for the class members are carried across too.
Doesn't do this.
I created a library which allows you to create JS-models for knockout and backbone out of c#-classes (mainly for domain-classes, so it comes with stuff like DataAnnotations-support, etc).
I added support for Typescript, as well as a small tool to create the files directly.
Check it out and if you have time, I'd love some feedback :)
https://jsmapper.codeplex.com/
Cheers,
Richard

Is there a way to easily get the JavaScript representation of a C# model?

I have an ASP.NET MVC application where I declare a few C# models for my data. However, I also process the data on client side and it would be nice if I could somehow get a JavaScript representation of a C# class so I do not have to re-declare the same data structures in JavaScript. Ideally, in my client code I would reference a script with class name as a query string parameter and it would return the JS code defining the constructor for the needed C# class. E.g.
<script src="/model/get?type=Myapp.User"></script>
Of course, it would all happen in runtime with help of reflection.
Is there any existing solution that does that? Thank you.
You can return instances of objects as JSON using built in JsonResult class, but for type information you will need to build something yourself (again likely returning as JSON).
Json.Encode(MyObject)
or get newtonsofts json library (its better), It has many options, including type information, which can be useful for inheritance.
However.... any circular references are problems. Quite often its better to make an anonymous object with a minimal object structure that your view needs, then encode that.

ASP.NET Web Service Results, Proxy Classes and Type Conversion

I'm still new to the ASP.NET world, so I could be way off base here, but so far this is to the best of my (limited) knowledge!
Let's say I have a standard business object "Contact" in the Business namespace. I write a Web Service to retrieve a Contact's info from a database and return it. I then write a client application to request said details.
Now, I also then create a utility method that takes a "Contact" and does some magic with it, like Utils.BuyContactNewHat() say. Which of course takes the Contact of type Business.Contact.
I then go back to my client application and want to utilise the BuyContactNewHat method, so I add a reference to my Utils namespace and there it is. However, a problem arises with:
Contact c = MyWebService.GetContact("Rob);
Utils.BuyContactNewHat(c); // << Error Here
Since the return type of GetContact is of MyWebService.Contact and not Business.Contact as expected. I understand why this is because when accessing a web service, you are actually programming against the proxy class generated by the WSDL.
So, is there an "easier" way to deal with this type of mismatch? I was considering perhaps trying to create a generic converter class that uses reflection to ensure two objects have the same structure than simply transferring the values across from one to the other.
You are on the right track. To get the data from the proxy object back into one of your own objects, you have to do left-hand-right-hand code. i.e. copy property values. I'll bet you that there is already a generic method out there that uses reflection.
Some people will use something other than a web service (.net remoting) if they just want to get a business object across the wire. Or they'll use binary serialization. I'm guessing you are using the web service for a reason, so you'll have to do property copying.
You don't actually have to use the generated class that the WSDL gives you. If you take a look at the code that it generates, it's just making calls into some .NET framework classes to submit SOAP requests. In the past I have copied that code into a normal .cs file and edited it. Although I haven't tried this specifically, I see no reason why you couldn't drop the proxy class definition and use the original class to receive the results of the SOAP call. It must already be doing reflection under the hood, it seems a shame to do it twice.
I would recommend that you look at writing a Schema Importer Extension, which you can use to control proxy code generation. This approach can be used to (gracefully) resolve your problem without kludges (such as copying around objects from one namespace to another, or modifying the proxy generated reference.cs class only to have it replaced the next time you update the web reference).
Here's a (very) good tutorial on the subject:
http://www.microsoft.com/belux/msdn/nl/community/columns/jdruyts/wsproxy.mspx

Categories

Resources