Compare Property values of two json objects in c# - c#

I have a two json objects like this below,
Json 1:
{
"data": {
"firstName": "xxx",
"lastName": "yyy",
"age": "29"
}
}
Json 2:
{
"data": {
"firstName": "aaa",
"lastName": "yyy",
"age": "30",
"location": "USA"
},
"meta": {
"browser": "chrome",
"ip": "999.999.999"
}
}
How can i compare properties of json 1 with json 2 and return the bool value if values are equal ?
From the above example the firstName value is different in both json objects so the result will return bool value as false , otherwise it will return true.
Please help, thanks in advance !!!

Approach #1 - Using JObject from Newtonsoft.Json Library
var json1 = File.ReadAllText("json1.json");
var json2 = File.ReadAllText("json2.json");
var jObj1 = JObject.Parse(json1);
var jObj2 = JObject.Parse(json2);
if (jObj1["data"]["firstName"] != null && jObj2["data"]["firstName"] != null && jObj1["data"]["firstName"].ToString() == jObj2["data"]["firstName"].ToString())
{
//condition is true
Console.WriteLine("true");
}
else
{
//condition is false
Console.WriteLine("false");
}
Approach #2 - Using Modal & JsonConvert from Newtonsoft.Json Library. I have used json2csharp to convert the json to c# class
public class Data
{
public string firstName { get; set; }
public string lastName { get; set; }
public string age { get; set; }
public string location { get; set; }
}
public class Meta
{
public string browser { get; set; }
public string ip { get; set; }
}
public class Root
{
public Data data { get; set; }
public Meta meta { get; set; }
}
var jObj1 = JsonConvert.DeserializeObject<Root>(json1);
var jObj2 = JsonConvert.DeserializeObject<Root>(json2);
if (jObj1.data.firstName.Equals(jObj2.data.firstName))
{
Console.WriteLine("true");
}
else
{
Console.WriteLine("false");
}

Related

Extract value from Json format in C#

I am trying to extract the objectId and displayName from below JSON format http result. But I have not been successful at all. can someone suggest me to extract objectId and displayName.
My code so far:
var httpClient = new HttpClient
{
BaseAddress = new Uri("https://graph.windows.net/")
};
string URI = $"/{TenantID}/users?$filter=userPrincipalName%20eq%20'{EmailAddress}'&api-version=1.6";
httpClient.DefaultRequestHeaders.Remove("Authorization");
httpClient.DefaultRequestHeaders.Add("Authorization", "Bearer " + MSGraphToken);
HttpResponseMessage response = await httpClient.GetAsync(URI).ConfigureAwait(false);
var HttpsResponse = await response.Content.ReadAsStringAsync();
dynamic Result = JsonConvert.DeserializeObject<object>(HttpsResponse);
UserDetails UserDetailsList = new UserDetails();
dynamic OdataResult = Result["value"];
if (Result != null)
{
UserDetailsList.DisplayName = OdataResult.displayName ?? "N/A";
UserDetailsList.ObjectID = OdataResult.objectId ?? "N/A";
}
return UserDetailsList;
JSON result:
{{
"value": [
{
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"objectId": "00000000-0000-0000-0000-000000000000",
"assignedPlans": [
{
"assignedTimestamp": "2022-09-06T20:38:49Z",
"capabilityStatus": "Enabled",
"service": "RMSOnline",
"servicePlanId": "00000000-0000-0000-0000-000000000000"
},
{
"assignedTimestamp": "2022-09-06T20:38:49Z",
"capabilityStatus": "Enabled",
"service": "Adallom",
"servicePlanId": "00000000-0000-0000-0000-000000000000"
},
],
"displayName": "Sachin Tendulkar (alt_sachint)",
"employeeId": "000000",
"userPrincipalName": "alt_sachint#pme.gbl.msidentity.com"
}
]
}}
just use Parse if you only need to get a couple of values. In this case you don't need to create classes
var json = await response.Content.ReadAsStringAsync();
var value = JObject.Parse(json)["value"];
string objectId = (string)value[0]["objectId"]; // 00000000-0000-0000-0000-000000000000
string displayName = (string)value[0]["displayName"]; // Sachin Tendulkar (alt_sachint)
and remove an extra "{ }" from the edges of your json
First of all your posted JSON is invalid, I have corrected it.
{
"value": [{
"odata.type": "Microsoft.DirectoryServices.User",
"objectType": "User",
"objectId": "00000000-0000-0000-0000-000000000000",
"assignedPlans": [{
"assignedTimestamp": "2022-09-06T20:38:49Z",
"capabilityStatus": "Enabled",
"service": "RMSOnline",
"servicePlanId": "00000000-0000-0000-0000-000000000000"
},
{
"assignedTimestamp": "2022-09-06T20:38:49Z",
"capabilityStatus": "Enabled",
"service": "Adallom",
"servicePlanId": "00000000-0000-0000-0000-000000000000"
}
],
"displayName": "Sachin Tendulkar (alt_sachint)",
"employeeId": "000000",
"userPrincipalName": "alt_sachint#pme.gbl.msidentity.com"
}]
}
Then you should deserialize the json to a class object.
Root obj = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class AssignedPlan
{
public DateTime assignedTimestamp { get; set; }
public string capabilityStatus { get; set; }
public string service { get; set; }
public string servicePlanId { get; set; }
}
public class Root
{
public List<Value> value { get; set; }
}
public class Value
{
[JsonProperty("odata.type")]
public string odatatype { get; set; }
public string objectType { get; set; }
public string objectId { get; set; }
public List<AssignedPlan> assignedPlans { get; set; }
public string displayName { get; set; }
public string employeeId { get; set; }
public string userPrincipalName { get; set; }
}
So you can get the List of Value by obj.value which is a List of Value. Value class has properties objectId and employeeId .
You can use foreach or for or LINQ to fetch these properties accordingly.
you can get using dynamic also but i recommended to use strong type
Logic to get values
Using Strong Type
private void ReadJson()
{
string json = #"{""value"":[{""odata.type"":""Microsoft.DirectoryServices.User"",""objectType"":""User"",""objectId"":""00000000 - 0000 - 0000 - 0000 - 000000000000"",""assignedPlans"":[{""assignedTimestamp"":""2022 - 09 - 06T20: 38:49Z"",""capabilityStatus"":""Enabled"",""service"":""RMSOnline"",""servicePlanId"":""00000000 - 0000 - 0000 - 0000 - 000000000000""},{""assignedTimestamp"":""2022 - 09 - 06T20: 38:49Z"",""capabilityStatus"":""Enabled"",""service"":""Adallom"",""servicePlanId"":""00000000 - 0000 - 0000 - 0000 - 000000000000""},],""displayName"":""Sachin Tendulkar(alt_sachint)"",""employeeId"":""000000"",""userPrincipalName"":""alt_sachint #pme.gbl.msidentity.com""}]}";
var response = JsonConvert.DeserializeObject<Result>(json);
var objid = response.value[0].objectId;
var displayname = response.value[0].displayName;
// using for loop
foreach( var res in response.value)
{
objid = res.objectId;
displayname = res.displayName;
}
// you can use linq if you need object id and display name for specific condition
}
Classes
public class Result
{
public List<Response> value { get; set; }
}
public class Response
{
public string objectId { get; set; }
public string displayName { get; set; }
[JsonProperty("odata.type")]
public string odatatype { get; set; }
public string objectType { get; set; }
public List<AssignedPlan> assignedPlans { get; set; }
public string employeeId { get; set; }
public string userPrincipalName { get; set; }
}
public class AssignedPlan
{
public DateTime assignedTimestamp { get; set; }
public string capabilityStatus { get; set; }
public string service { get; set; }
public string servicePlanId { get; set; }
}
using dynamic
// 2. using dynamic
dynamic Result = JsonConvert.DeserializeObject<object>(json);
JArray jsonObject = JArray.FromObject(Result["value"]);
//JArray jsonObject = JArray.Parse(Result["value"]);
foreach (JObject content in jsonObject.Children<JObject>())
{
// you can get value from one of the approach
// 1. Approach
foreach (JProperty prop in content.Properties().Where(p => p.Name == "objectId"))
{
objid = prop.Value.ToString();
}
foreach (JProperty prop in content.Properties().Where(p => p.Name == "displayName"))
{
displayname = prop.Value.ToString();
}
// 2. Apprach
foreach (JProperty prop in content.Properties())
{
if (prop.Name == "objectId")
{
objid = prop.Value.ToString();
}
else if(prop.Name == "displayName")
{
displayname = prop.Value.ToString();
}
}
}
you can get value by following #Serge answer using dynamic if it is always one object in response(value node) but as per your sample it is array so you need to use Jarray or loop to get each value.

C#, JSON.net Loop through and store Jobject objects

New to both C# and to using JSON. Trying to make something that works with some JSON from a web API in the following format. Would like to loop through and store the secondUser_id and and the status for later use.
{
"user_list": [
{
"user_id": "12345678910",
"secondUser_id": "5428631729616515697",
"member_since": "1521326679",
"member_since_date": "2018-03-32",
"function": "test",
"rank_int": "1",
"status": "0"
},
{
"user_id": "11345638910",
"secondUser_id": "5428631729616515697",
"member_since": "1521326679",
"member_since_date": "2018-03-32",
"function": "test",
"rank_int": "1",
"status": "0"
},
{
"user_id": "13452578910",
"secondUser_id": "12390478910",
"member_since": "12316578910",
"member_since_date": "2018-03-32",
"function": "test",
"rank_int": "1",
"status": "0"
}
],
"returned": 3
}
string jsonUrl = GetJSON("url");
JObject UsersJObject = JObject.Parse(jsonUrl);
JToken user = UsersJObject["user_list"].First["secondUser_id"];
Console.WriteLine("User ID: " + user);
This will get the first entry but I'm not sure what to use for a enumerator?
try something like this:
foreach (var obj in UsersJObject["user_list"] as JArray)
{
Console.WriteLine(obj["secondUser_id"]);
}
You can iterate over elements of a JArray, and user_list will be of that type, cast it and you can iterate it in a foreach loop.
I will recommend you to use JsonConvert.DeserializeObject<T>.
This can help you to use objects easily
public class UserList
{
public string user_id { get; set; }
public string secondUser_id { get; set; }
public string member_since { get; set; }
public string member_since_date { get; set; }
public string function { get; set; }
public string rank_int { get; set; }
public string status { get; set; }
}
public class JsonData
{
public List<UserList> user_list { get; set; }
public int returned { get; set; }
}
Use like this.
string jsonUrl = GetJSON("url");
JsonData UsersJObject = JsonConvert.DeserializeObject<JsonData>(jsonUrl);
foreach (var obj in UsersJObject.user_list)
{
Console.WriteLine(obj.secondUser_id);
}

Use Linq or C# to parse Json

I am getting familiar with C# and Linq and appreciate any help. It should be easy for someone who works with it. I have a Json object that returns contact information. I also have a list of ids. I need to compare the list to the Json object and wherever the value in the list matches the userclientcode in the Json object, I need to extract the following information (only for the matches):
clienttaxonomy (if not empty)
fullname (if not empty)
[0]contactdata ( -> email if not null or empty)
[1]contactdata (-> address if not null or empty)
[2]contactdata (-> phone number if not null or empty)
First List
var fileContactIds = new List<string> { "5678765", "2135123", "12341234", "341234123", "12341234123", "2341234123", "341234123", "123412341", "13342354",
"12342341", "123412322", "163341234", "2345234115", "8967896", "75626234 };
JSON object returned with:
return JsonConvert.DeserializeObject<RelatedContacts>(json)?.list;
This is the Json object:
[![Json object][1]][1]
This is the Json string (unescaped):
{
"type": "com.kurtosys.api.userprofile.domain.RelatedContactList",
"list": [{
"objectlistid": 5678765,
"objectlisttypeid": 4567876,
"objectlistname": "ALL.National",
"clienttaxonomyid": 765677,
"clienttaxonomy": "National Wholesaler",
"order": 1,
"contacts": [{
"personid": 7654345678,
"fullname": "Person Jallo",
"userid": 876567,
"userclientcode": "341234123",
"contactdetails": [{
"contactid": 8765567,
"contacttypeid": 4565,
"contactdata": "person.contact#site.com"
}, {
"contactid": 876545678,
"contacttypeid": 4565,
"contactdata": "Baltimore,MD,21209,United States"
}, {
"contactid": 87654567,
"contacttypeid": 4584,
"contactdata": "410-413-2640"
}]
}]
}, {
"objectlistid": 765678,
"objectlisttypeid": 40400461,
"objectlistname": "RM.Internal",
"clienttaxonomyid": 7567898,
"clienttaxonomy": "Internal Regional Wholesaler",
"order": 2,
"contacts": [{
"personid": 56789876,
"fullname": "Jackson Man",
"userid": 876567,
"userclientcode": "1012275",
"contactdetails": [{
"contactid": 309598309,
"contacttypeid": 76546,
"contactdata": "mister.jackson##site.com.com"
}, {
"contactid": 876567,
"contacttypeid": 4581,
"contactdata": "Baltimore,MD,21209,United States"
}, {
"contactid": 876567,
"contacttypeid": 2342,
"contactdata": "123-413-2604"
}]
}]
}, {
"objectlistid": 309571364,
"objectlisttypeid": 40400461,
"objectlistname": "RM.External",
"clienttaxonomyid": 309580710,
"clienttaxonomy": "External Regional Wholesaler",
"order": 3,
"contacts": [{
"personid": 302736188,
"fullname": "Phal Sumi",
"userid": 303826019,
"userclientcode": "163341234",
"contactdetails": [{
"contactid": 309598253,
"contacttypeid": 2342,
"contactdata": "misters.emailas#site.com"
}, {
"contactid": 309611930,
"contacttypeid": 2342,
"contactdata": "Baltimore,MD,21209,United States"
}, {
"contactid": 34234132,
"contacttypeid": 3422,
"contactdata": "342-803-1793"
}]
}]
}]
}
How do I
1] Select using Linq and Lambdas and put in a list fullname, email, address etc from the deserialized object ?
2]compare with first list and only transfer those items where the userclientcode == the number in list A.
I have tried:
var query5 = relatedContact.Where(s => s.objectlistid == Convert.ToInt64(contacts.Select(t => t.id)))
var selected = relatedContact.Where(p => p.contacts
.Any(a => fileContactIds.Contains(p.contacts))
.ToList();
var query2 = relatedContact.Where(s => s.objectlistid == Convert.ToInt64(contacts.Select(t => t.id)))
.Select(s => new
{
Description = s.clienttaxonomy,
Fullname = s.contacts[0].fullname,
Email = s.contacts[0].contactdetails[0].contactdata,
Address = s.contacts[0].contactdetails[1].contactdata,
PhoneNumber = s.contacts[0].contactdetails[2].contactdata
});
But don't really know what I'm doing it seems. Any suggestions on how to get the required sections ? I think part of the reason is that the contactdata is a list.
Thanks all
You can create a classes for the desearlization of JSON Object like this
public class Rootobject
{
public string type { get; set; }
public List[] list { get; set; }
}
public class List
{
public int objectlistid { get; set; }
public int objectlisttypeid { get; set; }
public string objectlistname { get; set; }
public int clienttaxonomyid { get; set; }
public string clienttaxonomy { get; set; }
public int order { get; set; }
public Contact[] contacts { get; set; }
}
public class Contact
{
public long personid { get; set; }
public string fullname { get; set; }
public int userid { get; set; }
public string userclientcode { get; set; }
public Contactdetail[] contactdetails { get; set; }
}
public class Contactdetail
{
public int contactid { get; set; }
public int contacttypeid { get; set; }
public string contactdata { get; set; }
}
And then to extract the selected information we can also create a another class like
public class ExtractedInfo
{
public string ocClientTaxonomy { get; set; }
public string ocFullName { get; set; }
public CTDetails ocContactDetails { get; set; }
}
public class CTDetails
{
public string ocCTAddress { get; set; }
public string ocCTEmail { get; set; }
public string ocCTPhoneNumber { get; set; }
}
Now we have to find all the data from JSON
var fileContactIds = new List<string> { "5678765", "2135123", "12341234", "341234123", "12341234123", "2341234123", "341234123", "123412341", "13342354", "12342341", "123412322", "163341234", "2345234115", "8967896", "75626234" };
//Read JSON from txt file. You can do it by your way
string myjson = File.ReadAllText("Some.txt");
string ctphno, ctadd, ctemail, cltax, ctfullname;
List<ExtractedInfo> ei = new List<ExtractedInfo>();
CTDetails ctdtl = new CTDetails();
ExtractedInfo eiex = new ExtractedInfo();
//Deserialize the JSON string to Object.
Rootobject AllData = JsonConvert.DeserializeObject<Rootobject>(myjson);
//Finding all data in List Class
foreach(List lst in AllData.list)
{
cltax = lst.clienttaxonomy; // you can directly put eiex.ocClientTaxonomy = lst.clienttaxonomy;
foreach(Contact ct in lst.contacts)
{
//To check if value in the list matches the objectlistid in the Json object
if(fileContactIds.Contains(lst.objectlistid.ToString()))
{
ctfullname = ct.fullname; // you can directly put eiex.ocFullName = ct.fullname;
foreach(Contactdetail ctd in ct.contactdetails)
{
//Here we are trying to find the Match for Email.
if(Regex.IsMatch(ctd.contactdata, #"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase))
{
ctemail = ctd.contactdata;
ctdtl.ocCTEmail = ctemail;
}
//Here We trying to find the match for Phone Number.
else if(Regex.IsMatch(ctd.contactdata, #"\(?\d{3}\)?-? *\d{3}-? *-?\d{4}", RegexOptions.IgnoreCase))
{
ctphno = ctd.contactdata;
ctdtl.ocCTPhoneNumber = ctphno;
}
//If NOthing matches than it might be address (Assumed)
else
{
ctadd = ctd.contactdata;
ctdtl.ocCTAddress = ctadd;
}
}
eiex.ocFullName = ctfullname;
}
}
eiex.ocClientTaxonomy = cltax;
eiex.ocContactDetails = ctdtl;
ei.Add(eiex);
}
Hope this helps and fit in your requirements.

RestSharp :Getting null from the result.Data althouh at the time of debug result has JSON returned

I am using RestSharp and trying to deserialize the JSON result set and when I run the code I'm getting null from the result.Data although at the time of debugging the result has JSON returned.
private static void GetPanelList()
{
var client = new RestClient("http://CCCCCC.XXXXXX.com/API/v3/mailinglists/ML_dfgfghfghfh/contacts");
var request = new RestRequest(Method.GET);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("x-api-token", "JHFKFKJFYILIOROIY");
// IRestResponse response = client.Execute(request);
var result = client.Execute<List<PanelList>>(request);
foreach(var i in result.Data)
{
foreach(var j in i.elements)
{
Console.WriteLine(j.firstName);
}
}
Here is my POCO:
public class PanelList
{
public List<elements> elements { get; set; }
}
public class elements
{
public string id { get; set; }
public string firstName { get; set; }
public string lastName { get; set; }
public string email { get; set; }
public string externalDataReference { get; set; }
public List<EmbededData> ED { get; set; }
public List<ResponseHistory> RH { get; set; }
public List<EmailHistory> EH { get; set; }
}
and here is how my json result look like that am trying to parse.
{ "result": {
"elements": [
{
"id": "MLRP_b7q690QRSqCxVuR",
"firstName": "S1-User1-firstname",
"lastName": "S1-U2-lastname",
"email": "S1U1#XXXX.org.au",
"externalDataReference": null,
"embeddedData": {
"DateTaken": "20160519",
"TriggerResponseID": "R_3fE6zgBzLa24dgD",
"TriggerSurveyID": "SV_3TXTMnJlsUxVGRL"
},
"language": null,
"unsubscribed": false,
"responseHistory": [
{
"responseId": "R_3fE6zgBzLa24dgD",
"surveyId": "SV_3TXTMnJlsUxVGRL",
"date": "2016-05-20T04:09:09Z",
"emailDistributionId": null,
"finishedSurvey": true
}
],
"emailHistory": [
{
"emailDistributionId": "EMD_41wVLKlQaADQBcF",
"date": "2016-05-24T00:33:02Z",
"type": "Invite",
"result": "Success",
"surveyId": "SV_8wFieltINfFL2gl",
"read": false
}
]
}]}}
Shouldn't you be reading into a result "container" object?
container class:
public class PanelListContainer
{
public PanelList result { get; set; }
}
fetch code:
var result = client.Execute<PanelListContainer>(request);

Newtonsoft JSON Deserialize AND jsonfreeze

I have a two simple PHP class
class Order{
public $orderNo;
public $lines = array();
public $paid = false;
public function addLine(OrderLine $line) {
$this->lines[] = $line;
}
public function setPaid($paid = true) {
$this->paid = true;
}
}
class OrderLine{
public function __construct($item, $amount){
$this->item = $item;
$this->amount = $amount;
}
public $item;
public $amount;
public $options;
}
Serialize object uses https://github.com/mindplay-dk/jsonfreeze
...
$json = new JsonSerializer;
$data = $json->serialize($order);
Have output:
{
"#type": "Order",
"orderNo": 123,
"lines": [{
"#type": "OrderLine",
"item": "milk \"fuzz\"",
"amount": 3,
"options": null
},{
"#type": "OrderLine",
"item": "cookies",
"amount": 7,
"options": {
"#type": "#hash",
"flavor": "chocolate",
"weight": "1\/2 lb"
}
}],
"paid": true
}
Send the string XMLRPC in VB.NET
As using Newtonsoft JSON get a live object?
As well as how to create a compatible format by analogy with the json string of living VB.net OR C# object?
Here's something you could start with. You create some classes with properties which represent the JSON Format (untested code, just as idea):
public class MyData
{
[JsonProperty("#type")]
public string Type { get; set; }
[JsonProperty("#orderNo")]
public int OrderNo { get; set;
[JsonProperty("paid")]
public bool Paid { get; set; }
[JsonProperty("lines")]
public List<MyDataLine> Lines { get; set; }
}
public class MyDataLines
{
[JsonProperty("#type")]
public string Type { get; set; }
[JsonProperty("options")]
public MyDataLinesOptions Options { get; set; }
// ... more
}
public class MyDataLinesOptions
{
// ... more
}
Then you can serialize and deserialize the the data like this:
string json = "the json data you received";
MyData myData = JsonConvert.DeserializeObject<MyData>(json);
// ...
json = JsonConvert.SerializeObject(myData);
"#type": "Order"
and
"#type": "OrderLine",
this is not a property, this is an indication of the type of the object

Categories