C# Unit Testing - Assertions on JSON - c#

I am just playing around with some Json and Fluentassertions, I am able to make a call to an API successfully, get the results, deserialize them but for some reason when i get to do an assertion on the response its losing the data and it empty. I have debugged, can see the data flowing through and then losing it during assertion.
Any help appreciated.
{
[TestClass]
public class UnitTest1
{
HttpClient client = new HttpClient();
[TestMethod]
public void ActorNotInSeason6Episode1()
{
try
{
//test = extent.CreateTest("Test 1");
HttpResponseMessage respone = client.GetAsync("https://api.themoviedb.org/3/tv/1399/season/6/episode/1/credits?api_key=").Result;
Assert.IsTrue(respone.IsSuccessStatusCode.Equals(true));
string ResponseMessage = respone.Content.ReadAsStringAsync().Result;
Actors actors = JsonConvert.DeserializeObject<Actors>(ResponseMessage);
//var a = Actors.cast["cast"];
//var names = a.Children[];
//var a = actors.cast.Children();
actors.cast.Should().Contain("Emilia Clarke", "Test");
}
catch(AssertFailedException)
{
Assert.Fail();
}
}
}
}
class Actors
{
public JArray cast { get; set; }
public JArray guest_stars { get; set; }
}
}
JSON
{[
{
"character": "Daenerys Targaryen",
"credit_id": "5256c8af19c2956ff60479f6",
"gender": 1,
"id": 1223786,
"name": "Emilia Clarke",
"order": 0,
"profile_path": "/lRSqMNNhPL4Ib1hAJxmDFBXHAMU.jpg"
}
]}

Here is fluentassertions extension for JSON, which contains many useful methods for asserting JSON:
Available extension methods
BeEquivalentTo()
ContainSingleElement()
ContainSubtree()
HaveCount()
HaveElement()
HaveValue()
MatchRegex()
NotBeEquivalentTo()
NotHaveElement()
NotHaveValue()
NotMatchRegex()
I am not an author of this library.

Using the following strongly typed definitions based on the expected JSON from themoviedb
public partial class RootObject {
[JsonProperty("cast")]
public Cast[] Cast { get; set; }
[JsonProperty("crew")]
public Crew[] Crew { get; set; }
[JsonProperty("guest_stars")]
public Cast[] GuestStars { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
}
public partial class Cast {
[JsonProperty("character")]
public string Character { get; set; }
[JsonProperty("credit_id")]
public string CreditId { get; set; }
[JsonProperty("gender")]
public long Gender { get; set; }
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("order")]
public long Order { get; set; }
[JsonProperty("profile_path")]
public string ProfilePath { get; set; }
}
public partial class Crew {
[JsonProperty("id")]
public long Id { get; set; }
[JsonProperty("credit_id")]
public string CreditId { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("department")]
public string Department { get; set; }
[JsonProperty("job")]
public string Job { get; set; }
[JsonProperty("gender")]
public long Gender { get; set; }
[JsonProperty("profile_path")]
public string ProfilePath { get; set; }
}
You would need to do the following in your test
//...
var actors = JsonConvert.DeserializeObject<RootObject>(ResponseMessage);
//Assert
actors.Cast.Should().Contain(actor => actor.Name == "Emilia Clarke");

Related

Serializing Json to c# Class throwing error

I have a JSON returning from web like this
{
"data": {
"normal_customer": {
"0": {
"id": 1,
"name": "ALPHY"
}
},
"1": {
"id": 2,
"name": "STEVEN"
}
},
"luxury_customer": {
"3": {
"id": 8,
"name": "DEV"
}
}
}
}
I have created c# classes
public class StandardCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
public class LuxuryCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class Data
{
public StandardCustomers standard_Customers { get; set; }
public LuxuryCustomers luxury_Customers { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
}
When I use deserialize the response from the website using below c# code
var result1 = JsonConvert.DeserializeObject<Data>(response);
but result1.luxury_customers contains customerdetails which is null.
As suggested by #hellostone, I have modified to rootdata, then also
result1.luxury_customers contains customerdetails is null.
Any idea how to deserialize to c# class
When we pasted Json to visual studio, it generated classes as below
public class Rootobject
{
public Data data { get; set; }
}
public class Data
{
public Standard_Customers standard_Customers { get; set; }
public Luxury_Customers luxury_Customers { get; set; }
}
public class Standard_Customers
{
public _0 _0 { get; set; }
public _1 _1 { get; set; }
public _2 _2 { get; set; }
public _4 _4 { get; set; }
public _5 _5 { get; set; }
}
public class _0
{
public int id { get; set; }
public string name { get; set; }
}
individual classes are generated in standard customers , can we use list for this
I guess the problem is that index in luxury_customers starting not from zero. Try to use Dictionary<string,CustomersDetails> in LuxuryCustomers instead List<CustomersDetails>.
I've managed to deserialize Json with this classes:
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
}
public class Data
{
public Dictionary<string, CustomersDetails> normal_customer { get; set; }
public Dictionary<string,CustomersDetails> luxury_customer { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}
Deserialization code:
var result = JsonConvert.DeserializeObject<RootObject>(text);
P.S. I've remove one closing bracket after "ALPHY" element, to make Json valid, I hope it was typo and you're getting valid Json.
Your json string doesn't match with your defined classes. Your Json string should look like this if you want to preserve your class structure:
{
"data":{
"standard_Customers":{
"Customers_Details":[
{
"id":1,
"name":"ALPHY"
},
{
"id":2,
"name":"STEVEN"
}
]
},
"luxury_Customers":{
"Customers_Details":[
{
"id":8,
"name":"DEV"
}
]
}
}
}
Pay attention to the square brackets at the "Customers_Details" attribute.
Then the:
var result1 = JsonConvert.DeserializeObject<RootObject>(response);
call, will give you the right object back and it shouldn't be null, when using your class structure:
public class StandardCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class CustomersDetails
{
[JsonProperty("id")]
public int id { get; set; }
[JsonProperty("name")]
public string name { get; set; }
}
public class LuxuryCustomers
{
public List<CustomersDetails> Customers_Details { get; set; }
}
public class Data
{
public StandardCustomers standard_Customers { get; set; }
public LuxuryCustomers luxury_Customers { get; set; }
}
public class RootObject
{
public Data data { get; set; }
}

C# - How convert json string to class

How can I convert my json-string to class
this is my json
{
"$id": "1",
"Result": {
"$id": "2",
"dateTime": 23821964,
"list": [{
"$id": "3",
"UserId": 302,
"UID": "302_UID",
"Title": "شیدکو",
"Sender": "شیدکو",
"Answer": "",
"Comment": "test 2",
"ProductTitle": null,
"CommentId": 77,
"Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
"Date": 24302057,
"AnswerDate": -2123661683,
"AnswerEdit": false,
"CommentEdit": false,
"ForfeitCount": 0,
"RewardCount": 0,
"ThisCountReport": 2,
"Reported": [{
"$id": "4",
"BlockerId": 355,
"Title": "محتوای غیر اخلاقی",
"Date": -19527396,
"ForfeitCount": 0,
"RewardCount": 0
}, {
"$id": "5",
"BlockerId": 355,
"Title": "محتوای غیر مرتبط",
"Date": -19527382,
"ForfeitCount": 0,
"RewardCount": 0
}],
"Gem": 0
}, {
"$id": "6",
"UserId": 302,
"UID": "302_UID",
"Title": "شیدکو",
"Sender": "شیدکو",
"Answer": "",
"Comment": "test 2",
"ProductTitle": null,
"CommentId": 77,
"Logo": "http://example.com/Commercial/User/302/Logo/tmpF0BF.jpg",
"Date": 24302057,
"AnswerDate": -2123661683,
"AnswerEdit": false,
"CommentEdit": false
}]
},
"StatusCode": "Created",
"Description": null
}
And I do these step, but nothing happens
JObject json1 = JObject.Parse(strMyJson);
_CommentAdmindto flight = Newtonsoft.Json.JsonConvert.DeserializeObject<_CommentAdmindto>(json1.ToString());
_CommentAdmindto deserializedProduct = JsonConvert.DeserializeObject<_CommentAdmindto>(json);
_CommentAdmindto deserializedProduct1 = ConvertJsonToClass<_CommentAdmindto>(strMyJson);
JsonSerializer serializer = new JsonSerializer();
_CommentAdmindto p = (_CommentAdmindto)serializer.Deserialize(new JTokenReader(strMyJson), typeof(_CommentAdmindto));
And here is my class and function:
public static T ConvertJsonToClass<T>( string json)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
return serializer.Deserialize<T>(json);
}
}
public class _CommentAdmindto
{
public long dateTime { get; set; }
public IQueryable<CommentDtoAdmin> list { get; set; }
}
public class CommentDtoAdmin
{
public long UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public string ProductTitle { get; set; }
public long CommentId { get; set; }
public string Logo { get; set; }
public long Date { get; set; }
public long AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
}
Your model should be similar to this (For invalid c# names, you can use JsonProperty attribute) :
public class Reported
{
[JsonProperty("$id")]
public string id { get; set; }
public int BlockerId { get; set; }
public string Title { get; set; }
public int Date { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
}
public class List
{
[JsonProperty("$id")]
public string id { get; set; }
public int UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public object ProductTitle { get; set; }
public int CommentId { get; set; }
public string Logo { get; set; }
public int Date { get; set; }
public int AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
public int ThisCountReport { get; set; }
public List<Reported> Reported { get; set; }
public int Gem { get; set; }
}
public class Result
{
[JsonProperty("$id")]
public string id { get; set; }
public int dateTime { get; set; }
public List<List> list { get; set; }
}
public class RootObject
{
[JsonProperty("$id")]
public string id { get; set; }
public Result Result { get; set; }
public string StatusCode { get; set; }
public object Description { get; set; }
}
Now you can deserialize as
var result = JsonConvert.DeserializeObject<RootObject>(jsonstring);
BTW: http://json2csharp.com/ can help to guess your model when working with json.
You seem to be trying to deserialize in a lot of different ways but you don't have a full structure to actually match the json. You miss the outer class (representing the full object) and at least Newtonsoft.Json cannot deserialize to an IQueryable so I changed that to IEnumerable.
string strMyJson = "{\"$id\":\"1\",\"Result\":{\"$id\":\"2\",\"dateTime\":23826985,\"list\":[{\"$id\":\"3\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false,\"ForfeitCount\":0,\"RewardCount\":0,\"ThisCountReport\":2,\"Reported\":[{\"$id\":\"4\",\"BlockerId\":355,\"Title\":\"محتوای غیر اخلاقی\",\"Date\":-19527396,\"ForfeitCount\":0,\"RewardCount\":0},{\"$id\":\"5\",\"BlockerId\":355,\"Title\":\"محتوای غیر مرتبط\",\"Date\":-19527382,\"ForfeitCount\":0,\"RewardCount\":0}],\"Gem\":0},{\"$id\":\"6\",\"UserId\":302,\"UID\":\"302_UID\",\"Title\":\"شیدکو\",\"Sender\":\"شیدکو\",\"Answer\":\"\",\"Comment\":\"test 2\",\"ProductTitle\":null,\"CommentId\":77,\"Logo\":\"http://www.domain.com/Commercial/User/302/Logo/tmpF0BF.jpg\",\"Date\":24307078,\"AnswerDate\":-2123656662,\"AnswerEdit\":false,\"CommentEdit\":false}],\"StatusCode\":\"Created\",\"Description\":null}}";
var result = JsonConvert.DeserializeObject<Wrapper>(strMyJson);
with classes looking like this:
public class Wrapper
{
public _CommentAdmindto Result { get; set; }
}
public class _CommentAdmindto
{
public long dateTime { get; set; }
public IEnumerable<CommentDtoAdmin> list { get; set; }
}
CommentDtoAdmin is looking the same.
Though I must say that this only helps you with the deserialization.
Firstly, the $id" properties are synthetic properties added by Json.NET to track and preserve multiple references to the same object. For details, see PreserveReferencesHandling setting.
Thus, if you temporarily remove the "$id" properties, you can upload your JSON to http://json2csharp.com/ and get the following data model:
public class Reported
{
public int BlockerId { get; set; }
public string Title { get; set; }
public int Date { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
}
public class CommentDtoAdmin
{
public int UserId { get; set; }
public string UID { get; set; }
public string Title { get; set; }
public string Sender { get; set; }
public string Answer { get; set; }
public string Comment { get; set; }
public object ProductTitle { get; set; }
public int CommentId { get; set; }
public string Logo { get; set; }
public int Date { get; set; }
public int AnswerDate { get; set; }
public bool AnswerEdit { get; set; }
public bool CommentEdit { get; set; }
public int ForfeitCount { get; set; }
public int RewardCount { get; set; }
public int ThisCountReport { get; set; }
public List<Reported> Reported { get; set; }
public int Gem { get; set; }
}
public class Result
{
public int dateTime { get; set; }
public List<CommentDtoAdmin> list { get; set; }
}
public class RootObject
{
public Result Result { get; set; }
public string StatusCode { get; set; }
public string Description { get; set; }
}
I then modified the returned model as follows:
I used the name CommentDtoAdmin for the list type.
I set the type of the Description property to string.
Now your JSON can be deserialized and re-serialized as follows:
var settings = new JsonSerializerSettings
{
PreserveReferencesHandling = PreserveReferencesHandling.Objects,
};
var root = JsonConvert.DeserializeObject<RootObject>(json1, settings);
var json2 = JsonConvert.SerializeObject(root, Formatting.Indented, settings);
Note that Json.NET has no built-in logic for deserializing the interface IQueryable<T> to a concrete type, so I had to leave the property as public List<CommentDtoAdmin> list { get; set; }. You can always generate a queryable from the list using AsQueryable():
var queryable = root.Result.list.AsQueryable();
Sample fiddle.
I think you json string does not have correct syntax. It looks like a ']' (end of Array) and a final '}' is missing.
That's what the Visual Studio editor told me when making a json file out of your string after removing all the '\'

processing api output in vb.net or c#

After making an api call, the example below shows what a typical response would be.
{
"code":"success",
"message":"Data retrieved for email",
"data":{
"attributes":{
"EMAIL":"example#example.net",
"NAME" : "Name",
"SURNAME" : "surname"
},
"blacklisted":1,
"email":"example#example.net",
"entered":"2014-01-15",
"listid":[8],
"message_sent":[{
"camp_id" : 2,
"event_time" : "2013-12-18"
},
{ "camp_id" : 8,
"event_time" : "2014-01-03"
},
{ "camp_id" : 11,
"event_time" : "2014-01-07"
}],
"hard_bounces":[{
"camp_id" : 11,
"event_time" : "2014-01-07"
}],
"soft_bounces":[],
"spam":[{
"camp_id" : 2,
"event_time" : "2014-01-09"
}],
"unsubscription":{
"user_unsubscribe":[
{
"event_time":"2014-02-06",
"camp_id":2,
"ip":"1.2.3.4"
},
{
"event_time":"2014-03-06",
"camp_id":8,
"ip":"1.2.3.4"
}
],
"admin_unsubscribe":[
{
"event_time":"2014-04-06",
"ip":"5.6.7.8"
},
{
"event_time":"2014-04-16",
"ip":"5.6.7.8"
}
]
},
"opened":[{
"camp_id" : 8,
"event_time" : "2014-01-03",
"ip" : "1.2.3.4"
}],
"clicks":[],
"transactional_attributes":[
{
"ORDER_DATE":"2015-07-01",
"ORDER_PRICE":100000,
"ORDER_ID":"1"
},
{
"ORDER_DATE":"2015-07-05",
"ORDER_PRICE":500000,
"ORDER_ID":"2"
}
],
"blacklisted_sms":1
}
}
What I need to do is to be able to read / find and attribute name and its corresponding value. I also need to know the value of blacklisted.
I don't know how to interpret the output given to easily find and read attributes and their values and also get the value of blacklisted.
Maybe if I can get it into an array, I can cycle through the array to find the value pair I am looking for? Or maybe I am overthinking it and their is an easier way.
Please note: This example only shows 3 attribute:value pairs. other calls may output more than three attribute:value pairs.
The simplest way is: You are getting the response in the JSON format and you just need it to be seralized with the use of classes and Json.NET
public class Rootobject
{
public string code { get; set; }
public string message { get; set; }
public Data data { get; set; }
}
public class Data
{
public Attributes attributes { get; set; }
public int blacklisted { get; set; }
public string email { get; set; }
public string entered { get; set; }
public int[] listid { get; set; }
public Message_Sent[] message_sent { get; set; }
public Hard_Bounces[] hard_bounces { get; set; }
public object[] soft_bounces { get; set; }
public Spam[] spam { get; set; }
public Unsubscription unsubscription { get; set; }
public Opened[] opened { get; set; }
public object[] clicks { get; set; }
public Transactional_Attributes[] transactional_attributes { get; set; }
public int blacklisted_sms { get; set; }
}
public class Attributes
{
public string EMAIL { get; set; }
public string NAME { get; set; }
public string SURNAME { get; set; }
}
public class Unsubscription
{
public User_Unsubscribe[] user_unsubscribe { get; set; }
public Admin_Unsubscribe[] admin_unsubscribe { get; set; }
}
public class User_Unsubscribe
{
public string event_time { get; set; }
public int camp_id { get; set; }
public string ip { get; set; }
}
public class Admin_Unsubscribe
{
public string event_time { get; set; }
public string ip { get; set; }
}
public class Message_Sent
{
public int camp_id { get; set; }
public string event_time { get; set; }
}
public class Hard_Bounces
{
public int camp_id { get; set; }
public string event_time { get; set; }
}
public class Spam
{
public int camp_id { get; set; }
public string event_time { get; set; }
}
public class Opened
{
public int camp_id { get; set; }
public string event_time { get; set; }
public string ip { get; set; }
}
public class Transactional_Attributes
{
public string ORDER_DATE { get; set; }
public int ORDER_PRICE { get; set; }
public string ORDER_ID { get; set; }
}
Use Newtonsoft.Json library. One of the most powerful library.Parse your JSON to strongly typed C# object using json2csharp.com then just deserialize the string.
var model= JsonConvert.DeserializeObject<Classname>(result);
You'll need JSON.Net. Pasrse your JSON to strongly typed C# object using json2csharp.com then just deserialize the string using JsonConvert.Deserialize<RootObject>().
One way would be to:
a) Copy your JSON to Clipboard (CTRL+C)
b) On a Visual Studio class, click on EDIT-> Paste Special -> Paste JSON as classes. This will create the classes equivalent of your JSON for you. Your main object would be named as "Rootobject" and you can change this to whatever name you want.
c) Add System.Web.Extensions to your references
d) You can convert your JSON to class like so:
JavaScriptSerializer serializer = new JavaScriptSerializer();
Rootobject rootObject = serializer.Deserialize<Rootobject>(JsonString);
Where JsonString is your API output.

extract data from json in asp.net c#

I'm trying to extract some data from json. I've been looking for a solution either in JSS or Json.net but haven't been able to figure this problem out. this is how my Json looks like:
Note: i Have tested and the mapping and decentralization works! I'm looking for a way to extract specifc data from the json!
Thanks in Advance!
{
"tasks":[
{
"id":"tmp_fk1345624806538",
"name":"Gantt editor ",
"code":"",
"level":0,
"status":"STATUS_ACTIVE",
"start":1346623200000,
"duration":5,
"end":1347055199999,
"startIsMilestone":false,
"endIsMilestone":false,
"assigs":[
{
"resourceId":"tmp_3",
"id":"tmp_1345625008213",
"roleId":"tmp_1",
"effort":7200000
}
],
"depends":"",
"description":"",
"progress":0
},
{
"id":"tmp_fk1345624806539",
"name":"phase 1",
"code":"",
"level":1,
"status":"STATUS_ACTIVE",
"start":1346623200000,
"duration":2,
"end":1346795999999,
"startIsMilestone":false,
"endIsMilestone":false,
"assigs":[
{
"resourceId":"tmp_1",
"id":"tmp_1345624980735",
"roleId":"tmp_1",
"effort":36000000
}
],
"depends":"",
"description":"",
"progress":0
},
{
"id":"tmp_fk1345624789530",
"name":"phase 2",
"code":"",
"level":1,
"status":"STATUS_SUSPENDED",
"start":1346796000000,
"duration":3,
"end":1347055199999,
"startIsMilestone":false,
"endIsMilestone":false,
"assigs":[
{
"resourceId":"tmp_2",
"id":"tmp_1345624993405",
"roleId":"tmp_2",
"effort":36000000
}
],
"depends":"2",
"description":"",
"progress":0
}
],
"resources":[
{
"id":"tmp_1",
"name":"Resource 1"
},
{
"id":"tmp_2",
"name":"Resource 2"
},
{
"id":"tmp_3",
"name":"Resource 3"
}
],"roles":[
{
"id":"tmp_1",
"name":"Project Manager"
},
{
"id":"tmp_2",
"name":"Worker"
}
],
"canWrite":true,
"canWriteOnParent":true,
"selectedRow":0,
"deletedTaskIds":[],
}
i've already mapped as follow
public class Rootobject
{
public Task[] tasks { get; set; }
public Resource[] resources { get; set; }
public Role[] roles { get; set; }
public bool canWrite { get; set; }
public bool canWriteOnParent { get; set; }
public int selectedRow { get; set; }
public object[] deletedTaskIds { get; set; }
}
public class Task
{
public string id { get; set; }
public string name { get; set; }
public string code { get; set; }
public int level { get; set; }
public string status { get; set; }
public long start { get; set; }
public int duration { get; set; }
public long end { get; set; }
public bool startIsMilestone { get; set; }
public bool endIsMilestone { get; set; }
public Assig[] assigs { get; set; }
public string depends { get; set; }
public string description { get; set; }
public int progress { get; set; }
}
public class Assig
{
public string resourceId { get; set; }
public string id { get; set; }
public string roleId { get; set; }
public int effort { get; set; }
}
public class Resource
{
public string id { get; set; }
public string name { get; set; }
}
public class Role
{
public string id { get; set; }
public string name { get; set; }
}
and I need to extract following information from my json.(from specific Task in may json! for example the first one with id : tmp_fk1345624806538 ).
Note: i'm getting my json from a json file as follow:
string startDate; // this is what i need to extract
string endDate; // this is what i need to extract
string Progress; // this is what i need to extract
public void load()
{
GC.GClass l = new GC.GClass();
string jsonString = l.load(); // i get my json from a json file
Rootobject project = JsonConvert.DeserializeObject<Rootobject>(jsonString);
}
You can use LINQ to query the object quickly.
Task task = project.tasks.FirstOrDefault(t=> t.id == "tmp_fk1345624806538");
Test task, and if null then there was not task with matching id. If you are sure that there will be a matching task your can just use .First(), but it will throw an exception if there is no match in the list
You'll need to add a using System.Linq; if you don't have that already.

Access Elements in JSON File Using C#

I have an JSON result like this
{
"authenticationResultCode":"ValidCredentials",
"brandLogoUri":"http:\/\/dev.virtualearth.net\/Branding\/logo_powered_by.png",
"copyright":"Copyright © 2011 Microsoft and its suppliers. All rights reserved. This API cannot be accessed and the content and any results may not be used, reproduced or transmitted in any manner without express written permission from Microsoft Corporation.",
"resourceSets":[
{
"estimatedTotal":1,
"resources":[
{
"__type":"Location:http:\/\/schemas.microsoft.com\/search\/local\/ws\/rest\/v1",
"bbox":[
47.636257744012461,
-122.13735364288299,
47.643983179153814,
-122.12206713944467
],
"name":"1 Microsoft Way, Redmond, WA 98052",
"point":{
"type":"Point",
"coordinates":[
47.640120461583138,
-122.12971039116383
]
},
"address":{
"addressLine":"1 Microsoft Way",
"adminDistrict":"WA",
"adminDistrict2":"King Co.",
"countryRegion":"United States",
"formattedAddress":"1 Microsoft Way, Redmond, WA 98052",
"locality":"Redmond",
"postalCode":"98052"
},
"confidence":"High",
"entityType":"Address",
"geocodePoints":[
{
"type":"Point",
"coordinates":[
47.640120461583138,
-122.12971039116383
],
"calculationMethod":"InterpolationOffset",
"usageTypes":[
"Display"
]
},
{
"type":"Point",
"coordinates":[
47.640144601464272,
-122.12976671755314
],
"calculationMethod":"Interpolation",
"usageTypes":[
"Route"
]
}
],
"matchCodes":[
"Good"
]
}
]
}
],
"statusCode":200,
"statusDescription":"OK",
"traceId":"b0b1286504404eafa7e7dad3e749d570"
}
I want to get a list of objects, and every object will contain the value of coordinates
So how can access these element by name?
I am using C# as a code behind.
You can use package like Json.NET for this task.
and easily you can generate classes by giving json string from http://json2csharp.com/
then you can access properties of items as below
RootObject obj = JsonConvert.DeserializeObject<RootObject>(jsonText);
below are the classes generated from the json2csharp for given json
public class Point
{
public string type { get; set; }
public List<double> coordinates { get; set; }
}
public class Address
{
public string addressLine { get; set; }
public string adminDistrict { get; set; }
public string adminDistrict2 { get; set; }
public string countryRegion { get; set; }
public string formattedAddress { get; set; }
public string locality { get; set; }
public string postalCode { get; set; }
}
public class GeocodePoint
{
public string type { get; set; }
public List<double> coordinates { get; set; }
public string calculationMethod { get; set; }
public List<string> usageTypes { get; set; }
}
public class Resource
{
public string __type { get; set; }
public List<double> bbox { get; set; }
public string name { get; set; }
public Point point { get; set; }
public Address address { get; set; }
public string confidence { get; set; }
public string entityType { get; set; }
public List<GeocodePoint> geocodePoints { get; set; }
public List<string> matchCodes { get; set; }
}
public class ResourceSet
{
public int estimatedTotal { get; set; }
public List<Resource> resources { get; set; }
}
public class RootObject
{
public string authenticationResultCode { get; set; }
public string brandLogoUri { get; set; }
public string copyright { get; set; }
public List<ResourceSet> resourceSets { get; set; }
public int statusCode { get; set; }
public string statusDescription { get; set; }
public string traceId { get; set; }
}
Since you already appear to be using DataContractJsonSerializer, let's stick with that. The best way to deserialize json is to first define a model which will capture the relevant data e.g.
public class JsonModel
{
public int StatusCode { get; set; }
public string StatusDescription { get; set; }
public string TraceId { get; set; }
...
}
Next, decorate the model so it's fit for deserialization
[DataContract]
public class JsonModel
{
[DataMember(Name = "statusCode")]
public int StatusCode { get; set; }
[DataMember(Name = "statusDescription")]
public string StatusDescription { get; set; }
[DataMember(Name = "traceId")]
public string TraceId { get; set; }
...
}
Then finally, perform the deserialization
using (var memoryStream = new MemoryStream(Encoding.Unicode.GetBytes(jsonData)))
{
var serializer = new DataContractJsonSerializer(typeof(JsonModel));
var model = (JsonModel) serializer.ReadObject(memoryStream);
Console.WriteLine(model.StatusCode);
}
So how can access these element by name?
The other option for deserialization which would give you the ability to reference the properties by name would be to use a dynamic object e.g.
var model = new JavaScriptSerializer().Deserialize<dynamic>(jsonData);
Console.WriteLine(model["statusCode"]);
Add the classes for all Bing Maps REST Services from the URL below to your project:
JSON Data Contracts
Then, make sure that you add the using directive:
using BingMapsRESTService.Common.JSON;
and read the string as follows (where stream is a stream for your json):
var d = new DataContractJsonSerializer(typeof(Response));
var o = d.ReadObject(stream);

Categories