29

I am having issues with understanding how to make this happen.

Basically we have an API, the user sends a JSON of the format:

{
  "Profile":[
    {
      "Name":"Joe",
      "Last":"Doe",
      "Client":{
        "ClientId":"1",
        "Product":"Apple",
        "Message":"Peter likes apples"
      },
      "Date":"2012-02-14"
    }
  ]
}

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.

aSemy
  • 5,485
  • 2
  • 25
  • 51
user710502
  • 11,181
  • 29
  • 106
  • 161

5 Answers5

55

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;
}
decates
  • 3,406
  • 1
  • 22
  • 25
L.B
  • 114,136
  • 19
  • 178
  • 224
  • 2
    Cool, whats the role of the Root class?, sorry if a newbie question :) – user710502 Apr 03 '12 at 07:00
  • Since your `Profile` array is inside of an object(json's root object doesn't have a name like xml). I named it `Root`, you can choose any name you want – L.B Apr 03 '12 at 07:02
  • @Malice Link is as I intended... I rolled back your update – L.B Jan 22 '16 at 19:19
  • 3
    @L.B Why is it important to you that the "t" in Json.Net is not part of the link? That's against web conventions, so there must be a good reason. Is it some kind of insider joke? – Raphael Schmitz May 31 '18 at 11:47
7

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.

Kux
  • 1,362
  • 1
  • 16
  • 31
Marek
  • 10,307
  • 8
  • 70
  • 106
1

Easiest way I know is to use JSON.Net by newtonsoft. To make it easier to understand, I always make matching classes in C# with the same name. Then its easier to deserialize it. As an example, if it is an array of objects in js, it will map to a list of object with the same names in C#. As for the date time, its a bit tricky. Id do the client side validation and Datetime.tryParse in the serverside, itll take care of the dashes or slashes.

var serializer = new JavaScriptSerializer();
List<abc> abcList = serializer.Deserialize<List<abc>>(PassedInJsonString);
Buzzzzzzz
  • 1,074
  • 13
  • 17
1

I know this is a long time question, but I would like to add one more option, which does not use third party libraries, and only uses stock .Net libraries, and is available from .Net Core 3.1 onwards.

First of all, I leave a link to the official Microsoft documentation (where you will find examples on how to serialize and deserialize json strings): https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-how-to

Let's build on your example. We have our starting json string:

{
   "Profile":[
      {
         "Name":"Joe",
         "Last":"Doe",
         "Client":{
            "ClientId":"1",
            "Product":"Apple",
            "Message":"Peter likes apples"
         },
         "Date":"2012-02-14"
      }
   ]
}

If we build a data structure that can hold that definition, it would be something like:

public class Root
{
  public List<Profile> Profile { get; set; }
}

public class Profile
{
  public string Name { get; set; }
  public string Last { get; set; }
  public Client Client { get; set; }
  public string Date { get; set; }
}

public class Client
{
  public string ClientId { get; set; }
  public string Product { get; set; }
  public string Message { get; set; }
}

Now, and finally the answer to how to deserialize a json string into a particular object without third party libraries:

Root root = JsonSerializer.Deserialize<Root>(json);

Where json is the variable that contains your json string.

I add another link of interest, the official documentation of the Deserialize(...) method: https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonserializer.deserialize

Something that is really useful is the exception that can be thrown, JsonException: https://learn.microsoft.com/en-us/dotnet/api/system.text.json.jsonexception

cesAR
  • 606
  • 5
  • 16
0

DataContractJsonSerializer does the job, but it uses more sophisticated format for DateTime serialization.