Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

asp.net - How to map JSON to C# Objects

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...