Linq JObject query - c#

I have some problems with jobject and jarray linq query. I get this error:
Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'.
My code:
string fetchResult = JsonConvert.SerializeObject(sidebar, Formatting.Indented);
JObject rss = JObject.Parse(fetchResult);
var jsonModel = from item in (JArray)rss["RegistrationCase"]
select new DataList
{
RegistrationTypeName = item["RegistrationTypeName"].Value<string>(), };
If i remove (Jarray) i get: Cannot access child value on Newtonsoft.Json.Linq.JProperty.
Json, jobject: e.g: i want RegistrationTypeName, FirstName and the value of JournalNumber.
{
"Status": null,
"RegistrationCase": {
"RegistrationTypeName": " ",
"ExpireDate": null,
"PersonId": 7,
"Person": {
"FirstName": " ",
"GenderValue": 2,
"Gender": 2,
},
"UserId": 7,
"User": {
"UserName": "NO-DOM\\wme",
"LastName": null,
"Id": 7,
},
"Transactions": [],
"Comments": [],
"CustomData": [
{
"Key": "JournalNumber",
"Value": "0654-84148-00000-25",
"Id": 3,
},
{
"Key": "IsConsentGiven",
"Value": "False",
"Id": 4,
},
{
],
"FileId": null,
"File": null,
"Id": 7,
}
}

u can get these values directly like :
var RegistrationTypeName = rss["RegistrationCase"]["RegistrationTypeName"];
var FirstName = rss["RegistrationCase"]["Person"]["FirstName"];
var JournalNumber = rss["RegistrationCase"]["CustomData"][0]["Value"];

Related

Odata2 Filtering parent or children of different types

I am trying to filter nested data but the catch is, the children I am also trying to filter are of a different type.
I have data that looks like this:
{
"value": [
{
"UserName": "scottketchum",
"FirstName": "Scott",
"LastName": "Ketchum",
"MiddleName": null,
"Gender": "Male",
"Age": null,
"Emails": [
"Scott#example.com"
],
"FavoriteFeature": "Feature1",
"Features": [],
"AddressInfo": [
{
"Address": "2817 Milton Dr.",
"City": {
"Name": "Albuquerque",
"CountryRegion": "United States",
"Region": "NM"
}
}
],
"HomeAddress": null
},
{
"UserName": "harryingram",
"FirstName": "Harry",
"LastName": "Ingram",
"MiddleName": null,
"Gender": "Male",
"Age": null,
"Emails": [
"Harry#example.com"
],
"FavoriteFeature": "Feature2",
"Features": [],
"AddressInfo": [
{
"Address": "123 Scott Ln.",
"City": {
"Name": "Nashville",
"CountryRegion": "United States",
"Region": "TN"
}
}
],
"HomeAddress": null
}
]
}
I need to be able to type the word "Scott" in my search field and return any person that has the name "Scott" or has an Address with the word "Scott" in it. So, ideally, the search would return both people.
void searchitemfromjson(string s)
{
var text = File.ReadAllText("D://jsontest.txt");
var jObject1 = JObject.Parse(text)["value"];
var searchs = new List<string>();
foreach (var item in jObject1)
{
var jObjitem = JObject.Parse(item.ToString());
IList<string> keys = jObjitem.Properties().Select(p => p.Name).ToList();
foreach (var k in keys)
{
if (k == "UserName")
{
if (jObjitem[k].ToString().Contains(s)) searchs.Add(jObjitem[k].ToString());
}
else if(k == "AddressInfo")
{
if(jObjitem["AddressInfo"][0]["Address"].ToString().Contains(s)) searchs.Add(jObjitem[k].ToString()); ;
}
}
}
}

How to extract all the values from this Json for Assertion?

My json response I get as a string. I am trying to write a generic Assertion method to check if a property name is equal to the correct value. I am not able to extract all entire json.. In the Children token only comes comes the first set. How can I get the entire json for this validation.
{
"id": 5,
"name": "NoTag",
"type": 0,
"query": null,
"parentId": null,
"ownerId": null,
"activeDirectoryId": null,
"hasChildren": false
}
"[
{
"id": 5,
"name": "NoTag",
"type": 0,
"query": null,
"parentId": null,
"ownerId": null,
"activeDirectoryId": null,
"hasChildren": false
},
{
"id": 6,
"name": "NewTag",
"type": 0,
"query": null,
"parentId": null,
"ownerId": "eccf46f3-348b-422e-8789-c163b5953b41",
"activeDirectoryId": null,
"hasChildren": false
},
{
"id": 7,
"name": "JohnTag",
"type": 0,
"query": null,
"parentId": null,
"ownerId": "eccf46f3-348b-422e-8789-c163b5953b41",
"activeDirectoryId": null,
"hasChildren": false
},
{
"id": 10,
"name": "MyTag",
"type": 0,
"query": null,
"parentId": null,
"ownerId": "eccf46f3-348b-422e-8789-c163b5953b41",
"activeDirectoryId": null,
"hasChildren": false
}
]"
//Here is the my Assertion method
public static void VerifyJsonString(IRestResponse response, string Property, string Value)
{
var res = response.Content; //using Restsharp
JArray jsonObject = JArray.Parse(response.Content);
foreach (JObject content in jsonObject.Children<JObject>())
{
foreach (JProperty prop in content.Properties().Where(p => p.Name == Property))
{
Assert.That(prop.Value, Is.EqualTo(Value));
}
}
}
You can get the property name for each element from the JSON array using the following code
JArray jArray = JArray.Parse(response.Content);
foreach (var element in jArray)
{
var propName = element["name"];
Assert.That(prop.Value, Is.EqualTo(propName));
}

get Specific Id from json file

this is my json file
{
{
"#odata.context": "https://api.onedrive.com/v1.0/$metadata#drives('me')/items('root')/children/$entity",
"createdBy": {
"application": {
"displayName": "Nopbackup",
"id": "4c190e01"
},
"user": {
"displayName": "pallav jha",
"id": "611c19eb038d5aa1"
}
},
"createdDateTime": "2016-05-12T07:25:36.463Z",
"cTag": "adDo2MTFDMTlFQjAzOEQ1QUExITEyNC42MzU5ODYzODk5MTI3MDAwMDA",
"eTag": "aNjExQzE5RUIwMzhENUFBMSExMjQuMw",
"id": "611C19EB038D5AA1!124",
"lastModifiedBy": {
"application": {
"displayName": "Nopbackup",
"id": "4c190e01"
},
"user": {
"displayName": "pallav jha",
"id": "611c19eb038d5aa1"
}
},
"lastModifiedDateTime": "2016-05-12T08:36:31.27Z",
"name": "Nopbackup",
"parentReference": {
"driveId": "611c19eb038d5aa1",
"id": "611C19EB038D5AA1!105",
"path": "/drive/root:"
},
"size": 0,
"webUrl": "https://onedrive.live.com/redir?resid=611C19EB038D5AA1!124",
"fileSystemInfo": {
"createdDateTime": "2016-05-12T07:25:36.463Z",
"lastModifiedDateTime": "2016-05-12T08:36:31.27Z"
},
"folder": {
"childCount": 0
}
}
}
i want to get this "id": "4c190e01" from json
dynamic value = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
string id = Convert.ToString(value.id[0]);
this is my code but i am not getting 4c190e01 id
rewrite your code as following...
dynamic valuePoco = Newtonsoft.Json.JsonConvert.DeserializeObject(result);
string id = Convert.ToString(valuePoco.createdBy.application.id);
You can use the path to the desired property. If you want to select the element with 4c190e01 as id, you can use
string id = value.createdBy.application.id;
or
string id = value.lastModifiedBy.application.id;
depending on your needs.
As it was pointed out, you'd need to fix your JSON first and remove the first { and the last }
First thing first, Your json is invalid.
You've to remove one { from top and } from the bottom and then use the following code:
dynamic jsonObj = JsonConvert.DeserializeObject(result);
string id = jsonObj.createdBy.application.id.ToString();

how to join two different JSON into single JSON in C#

My first JSON is as follows
[{
"UserId": 4,
"FirstName": "rupesh",
"LastName": "Abc",
"Email": "abc#gmail.com",
"Gender": "Male"
}]
My Second JSON is as follows
[{
"AccountId": 2,
"AccountName": "rupeshinfo",
"AccountDomain": null,
"RoleId": 1,
"UserId": 4
}, {
"AccountId": 3,
"AccountName": "Rameshinfo",
"AccountDomain": null,
"RoleId": 2,
"UserId": 4
}]
the result must be
{
"UserDetails": [{
"UserId": 4,
"FirstName": "rupesh",
"LastName": "Abc",
"Email": "abc#gmail.com",
"Gender": "Male"
}],
"AccountDetails": [{
"AccountId": 2,
"AccountName": "rupeshinfo",
"AccountDomain": null,
"RoleId": 1,
"UserId": 4
}, {
"AccountId": 3,
"AccountName": "Rameshinfo",
"AccountDomain": null,
"RoleId": 2,
"UserId": 4
}]
}
If you don't want to mess with string inserts you can go with (and I recommend so) using dynamic objects:
var javaScriptSerializer = new JavaScriptSerializer();
var userDetails = javaScriptSerializer.DeserializeObject(json1);
var accountDetails = javaScriptSerializer.DeserializeObject(json2);
var resultJson = javaScriptSerializer.Serialize(new {UserDetails = userDetails, AccountDetails = accountDetails});
You can deserialize them into two objects, create new anonimous type of these objects, and serialize them into the end one json:
JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
var result = jsonSerializer.Serialize(new
{
UserDetails = jsonSerializer.DeserializeObject(#"[{
'UserId': 4,
'FirstName': 'rupesh',
'LastName': 'Abc',
'Email': 'abc#gmail.com',
'Gender': 'Male'
}]"),
AccountDetails = jsonSerializer.DeserializeObject(#"[{
'AccountId': 2,
'AccountName': 'rupeshinfo',
'AccountDomain': null,
'RoleId': 1,
'UserId': 4
}, {
'AccountId': 3,
'AccountName': 'Rameshinfo',
'AccountDomain': null,
'RoleId': 2,
'UserId': 4
}]")
});
Try this
var jsonStr ='{"UserDetails":[{"UserId": 4,"FirstName": "rupesh","LastName": "Abc","Email": "abc#gmail.com","Gender": "Male"}]}'
var obj = JSON.parse(jsonStr);
obj['AccountDetails'].push({"AccountId": 2,"AccountName": "rupeshinfo","AccountDomain": null,"RoleId": 1,"UserId": 4}, {"AccountId": 3,"AccountName": "Rameshinfo","AccountDomain": null,"RoleId": 2,"UserId": 4});
jsonStr = JSON.stringify(obj);

DeserializeObject with newtonsoft.json without using Class

I have this Joson
{
"Sucess": true,
"Msg": "OK",
"Ret": {
"First": 0,
"Next": true,
"Total": 60,
"Itens": [
{
"ID": 212121,
"Name": "uuuuuuuuuuuuuuuuuuuuuuuu",
"LcID": 9898,
"Oclao": false,
"Lal": {
"ID": 12202,
"Name": "pppppppppppppppppp",
"Pais": "Brasil",
"Dtc": 0.0
},
"Subtipo": {
"ID": 7458,
"Desc": "mnmnmnmnn"
},
"Tipo": {
"Sit": "cor1",
"Sitrm": 0,
"Name": "Shsdfow"
},
"Qtde": 0,
"Qntcoes": 0,
"Pubum": "adfsdfsdfs",
"Evias": {
"arq": {
"Mo": [
"site.com"
],
"Moir": [
"site.com"
]
}
}
},
{
"ID": 9797878,
"Name": "uuuuuuuuuuuuuuuuuuuuuuuu",
"LcID": 9898,
"Oclao": false,
"Lal": {
"ID": 12332,
"Name": "pppppppppppppppppp",
"Pais": "Brasil",
"Dtc": 0.0
},
"Subtipo": {
"ID": 7458,
"Desc": "mnmnmnmnn"
},
"Tipo": {
"Sit": "cor1",
"Sitrm": 0,
"Name": "Shsdfow"
},
"Qtde": 0,
"Qntcoes": 0,
"Pubum": "adfsdfsdfs",
"Evias": {
"arq": {
"Mo": [
"site.com"
],
"Moir": [
"site.com"
]
}
}
}
]
}
}
I would read the array "items" by the field names without using a class to Deserialize, what I did so far was:
JObject jRetorno = JObject.Parse(strJson);
IList<JToken> jItens = jRetorno["Itens"].Children().ToList();
The example http://www.newtonsoft.com/json/help/html/SerializingJSONFragments.htm that uses a class for this, as my json always changes, wanted something like:
strReturn = jItens[1]["ID"];
strReturn = jItens[1]["Name"];
strReturn = jItens[2]["ID"];
strReturn = jItens[2]["Name"];
strReturn = jItens[3]["ID"];
strReturn = jItens[3]["Name"];
Thanks!
You're not that far off. The data you want is one level further down, inside the Ret object. Try it like this:
JObject jRetorno = JObject.Parse(strJson);
IList<JToken> jItens = jRetorno["Ret"]["Itens"].Children().ToList();
foreach (JToken jt in jItens)
{
Console.WriteLine(jt["ID"]);
Console.WriteLine(jt["Name"]);
}
Fiddle: https://dotnetfiddle.net/TwtGyz

Categories

Resources