Skip to content

Object Extensions

Dennis C. Mitchell edited this page Dec 17, 2017 · 12 revisions

The following extension methods for objects are provided:

bool IsSame(T obj)

This method returns true if the provided object variable and the current object variable (this) refer to the same object in memory. The method compares hashes and property values. Example:

[Test]
public void TestSameObjectInMemory() {
    Person p1 = new Person("Bob", "Jones");
    Person p2 = p1; //assign p2 to point to p1 (same object in memory)
    Assert.True(p1.IsSame(p2)); 
}

bool IsEqual(T obj)

This method returns true if the provided object variable and the current object variable (this) have the same property values. NOTE: this is a deep comparison. Example:

[Test]
public void TestEqualObjects() {
    Person p1 = new Person("Bob", "Jones");
    Person p2 = new Person("Bob", "Jones");
    Assert.False(p1.IsSame(p2));
    Assert.True(p1.IsEqual(p2));
}

bool IsEqual(T obj, string[] pathsToIgnore)

This method returns true if the provided object variable and the current object variable (this) have the same property values, ignoring all properties at the provided JSON paths. Example:

[Test]
public void TestEqualObjectsIgnoringSelectedProperties() {
    Person p1 = new Person(1, "Bob", "Jones");
    Person p2 = new Person(2, "Bob", "Jones");
    Assert.False(p1.IsEqual(p2));
    Assert.True(p1.IsEqual(p2, new string[] { "ID" })); //ignore ID
}

string ToJsonString()

This method serializes an object to a JSON string. Example:

[Test]
public void TestToJsonString() {
    string expectedJson =
        @"{
         ""ID"": 0,
         ""FirstName"": ""David"",
         ""LastName"": ""Parks""
        }";
    expectedJson = JToken.Parse(expectedJson).ToString(Formatting.Indented);
    Person p1 = new Person("David", "Parks");
    string actualJson = p1.ToJsonString();
    Assert.AreEqual(expectedJson, actualJson);
}

T FromJsonString(string json)

This method creates a new object of type T by deserializing the provided JSON string. When called from an object constructor, this method provides a convenient way to load an object with properties. Example:

[Test]
public void TestFromJsonString() {
    string json =
        @"{
         ""FirstName"": ""David"",
         ""LastName"": ""Parks""
        }";
    var p1 = new Person().FromJsonString(json);
    Person p2 = new Person("David", "Parks");
    Assert.True(p1.IsEqual(p2));
}

T FromJsonPath(string filePath, string objectPath)

This method creates a new object of type T by deserializing a JSON object or array in the provided JSON file at the provided path. When called from an object constructor, this method provides a convenient way to load an object with properties. NOTE: you can use "" or "/" instead of "." in the objectPath. Example:

[Test]
public void TestFromJsonPath2() {
    var p1 = new Person().FromJsonPath(@"DavidParks.json", "Contact");
    Person p2 = new Person("Jill", "Parks");
    Assert.True(p1.IsEqual(p2));
}

T FromJsonPath(string jsonFileObjectPath)

This method is equivalent to the above method, but it combines the filePath and objectPath into a single expression. Note that you can use a backslash or forward slash instead of period in the objectPath. Example:

[Test]
public void TestFromJsonPath3() {
    var p1 = new Person().FromJsonPath(@"DavidParks.json\Contact");
    Person p2 = new Person("Jill", "Parks");
    Assert.True(p1.IsEqual(p2));
}

T FromJsonPath(JToken jtoken, string jsonPath)

This method creates a new object of type T by deserializing a JSON object or array at the provided path in the provided JToken object. When called from an object constructor, this method provides a convenient way to load an object with properties. Example:

[Test]
public void TestFromJsonPath1() {
    string json =
       @"{
         ""FirstName"": ""David"",
         ""LastName"": ""Parks"",
         ""Contact"": {
             ""FirstName"": ""Jill"",
             ""LastName"": ""Parks""
            }
        }";
    var jtoken = JToken.Parse(json);
    var p1 = new Person().FromJsonPath(jtoken, "Contact");
    Person p2 = new Person("Jill", "Parks");
    Assert.True(p1.IsEqual(p2));
}

{ "minProjectManagementScore": 3, "persons": [ { "ID": 1, "FirstName": "Bob", "LastName": "Jones", "DateOfBirth": "1980-01-23T00:00:00", "Skills": [ { "Category": "Application Development", "Score": 3 }, { "Category": "Project Management", "Score": 3 } ] }, { "ID": 2, "FirstName": "Jill", "LastName": "Jones", "DateOfBirth": "1981-01-24T00:00:00", "Skills": [ { "Category": "Application Development", "Score": 2 }, { "Category": "Project Management", "Score": 1 } ] } ], "returns": [ { "ID": 1, "FirstName": "Bob", "LastName": "Jones", "DateOfBirth": "1980-01-23T00:00:00", "Skills": [ { "Category": "Application Development", "Score": 3 }, { "Category": "Project Management", "Score": 3 } ] } ] }


## T FromSql<T>(string jsonPath, string sqlForJsonFile, DbContext context)
This method creates a new object of type **T** by deserializing a JSON object or array from a SQL Server FOR JSON query.  When called from an object constructor, this method provides a convenient way to load an object with properties.  Example:

```SQL
-- PersonRepo\GetPersons\01.sql
declare @Person table (
	ID int,
	FirstName varchar(30),
	LastName varchar(30),
	DateOfBirth datetime
);
declare @Skill table (
	PersonID int,
	Category varchar(30),
	Score int
);

insert into @Person(ID,FirstName,LastName,DateOfBirth)
	values
		(1,'Bob','Jones','1980-01-23'),
		(2,'Jill','Jones','1981-01-24');

insert into @Skill(PersonID,Category,Score)
	values
		(1,'Application Development',3),
		(1,'Project Management',3),
		(2,'Application Development',2),
		(2,'Project Management',1);

declare @j varchar(max);
	set @j =
	(
		select ID,FirstName,LastName,DateOfBirth,
			(select  
				Category,Score
				from @Skill s
				where s.PersonID = p.ID
				for json path) Skills
			from @Person p
			for json path
	);

select @j [json];
[Test]
public void TestFromSql1() {
    using (var context = new JsonResultContext()) {
        var expectedJson = new List<Person>()
                .FromJsonPath(@"PersonRepo\GetPersons\01.json\persons");
        var actualJson = new List<Person>()
                .FromSql(@"PersonRepo\GetPersons\01.sql", context);

        Assert.True(expectedJson.IsEqual(actualJson));
    } 
}
Clone this wiki locally