user1122844
user1122844

Reputation: 87

json to object c#

I'm very new to json in c#. I'm supposed to make a project and provide my data to other fellow students by a mvc4 api. As a result I should be able to use others api too.

As I don't really have a clue how to parse the result of a request to an object, I'm asking here.

I have been requesting the page like this:

string url = "myUrl";

        WebRequest request = HttpWebRequest.Create(url);

        WebResponse response = request.GetResponse();

        StreamReader reader = new StreamReader(response.GetResponseStream());

        string urlText = reader.ReadToEnd();

the result of this request is as follows:

[{"Id":1,"Whose":1,"ReservedUserId":null,"ReservedBy":null,"ReservedSince":null,"City":"Gent","Street":"Sleepstraat","Number":12,"PostalCode":9000,"DateAdded":"2012-12-28T00:00:00","Description":"Momenteel geen omschrijving van dit pand","ContractLength":"12 maand","Surface":12,"MonthPrice":350,"AvailableSince":"2012-12-28T00:00:00","Rooms":2,"Maintenance":"Goed","Equipment":"Niet gemeubeld","Smokers":false,"Animals":false,"Housemates":2,"Toilet":"Gedeeld","Kitchen":"Gedeeld","Shower":"Gedeeld","Internet":"Ja, Telenet","Included":"Gas & Elektriciteit","Guarantee":350,"ContactEmail":"[email protected]","ContactTel":"0936001234"}]

How can I easaly convert this to a c# object so I can use it's properties?

Kind regards

Upvotes: 1

Views: 2532

Answers (2)

Gabriel
Gabriel

Reputation: 1652

Use JSON.Net to serialize and deserialize JSON. You can install it via NuGet.

If you have a class mapped to the JSON fields you could do something like this:

var chamber = JsonConvert.DeserializeObject<Chamber>(urlText);

You could also use a dynamic object

var chamber = JsonConvert.DeserializeObject<dynamic>(urlText);
int id = chamber.Id

Upvotes: 3

rs.
rs.

Reputation: 27417

Method 1:

First Create a Class with all variables matching json object

public class ClassName{
      public int id {get;set;}
      public int Whose {get;set;}
      public int ReservedUserId {get;set;}
      ...
      ...
      ... 
      public string ContactTel {get; set;}
}

Then you can use JavaScriptSerializer to deserialize the JSON object to new C# Custom object defined above

JavaScriptSerializer js = new JavaScriptSerializer();
ClassName [] c =  js.Deserialize<ClassName[]>(json);

Method 2:

You can use JSON.NET to deserialize JSON into dynamic objects

dynamic obj = JObject.Parse("{Id:1,Whose:1,ReservedUserId:null,ReservedBy:null}");
//dynamic obj = JObject.Parse(urlText);

then you can access object using

obj.Id;
obj.Whose;
obj.ReservedUserId;
obj.ReservedBy;

Upvotes: 0

Related Questions