Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map JSON to C# Objects

Tags:

json

c#

asp.net

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.

like image 336
user710502 Avatar asked Apr 03 '12 06:04

user710502


People also ask

How do I map one JSON object to another in C#?

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.

Can I map a JSON?

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.

What is JSON object in C?

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.


2 Answers

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; } 
like image 199
L.B Avatar answered Sep 24 '22 02:09

L.B


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.

like image 23
Marek Avatar answered Sep 22 '22 02:09

Marek