I am having issues with understanding how to make this happen.
Basically we have an API, the user sends a JSON of the format: (excuse the code if not perfect but you understand)
{"Profile": [{ "Name":"Joe", "Last :"Doe", "Client": { "ClientId":"1", "Product":"Apple", "Message":"Peter likes apples" }, "Date":"2012-02-14", }]}
Ok I'm not sure if I got that JSON formatted correctly but now here is my issue.
I have a class called Profile
with parameters Name, Last, and an object as one of its members called Client as well as property Date.
Something like this:
public class Profile { public string Name {get; set;} public string Last {get; set;} public Client client {get; set;} public DateTime dDate {get; set;} }
So basically, I am not sure how to grab the JSON and then map it to my object.
Any help with "helping" me understand would be much appreciated.
You can use a JSON library for this, for example Newtonsoft. Json which is free. It will map json to your types automatically. There is also a NuGet package available.
You can map the data types of your business model into JSON by using the examples. Data in JSON is either an object or an array. A JSON object is an unordered collection of names and values. A JSON array is an ordered sequence of values.
JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc. JSON stands for JavaScript Object Notation. The format was specified by Douglas Crockford.
You can use Json.NET to deserialize your json string as (with some modifications to your classes)
var yourObject = JsonConvert.DeserializeObject<Root>(jsonstring); public class Root { public Profile[] Profile; } public class Profile { public string Name { get; set; } public string Last { get; set; } public Client Client { get; set; } public DateTime Date { get; set; } } public class Client { public int ClientId; public string Product; public string Message; }
You can use a JSON library for this, for example Newtonsoft.Json which is free. It will map json to your types automatically.
Sample:
public static T Deserialize<T>(string json) { Newtonsoft.Json.JsonSerializer s = new JsonSerializer(); return s.Deserialize<T>(new JsonTextReader(new StringReader(json))); }
There is also a NuGet package available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With