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));
}
Related
I am trying to update a field which is inside a nested array or list. Using .Net Mongo Driver.
My Data structure is like:
[{
"_id": {
"$oid": "602cb1627661691f87bb1e6e"
},
"Events": [
{
"_id": "5ffd8d7f7d553920b9608f38",
"Roles": [
{
"_id": {
"$oid": "6017a4616609ff520ad2cd26"
}
}
],
"Sessions": [],
"IsProfileVisible": false,
"Aois": [],
"ViewOrder": 1,
"HelloWorldVideo": {
"Duration": 0,
"GroupId": "5ffd8d7f7d553920b9608f38",
"TagId": "TESTING",
"Title": "Testing title",
"VideoUrls": "https://cdn.azureedge.net/3734/helloworld/elephants-dream.webm",
"_id": {
"$oid": "603752797904007c5cc93e78"
},
"ProcessedVideoUrls": "https://cdn.azureedge.net/3734/helloworld/elephants-dream.webmProcessed",
"TagTypeId": null,
"Thumbnail": "https://cdn.azureedge.net/3734/helloworld/elephants-dream.webm",
"VideoType": "1",
"VttUrl": "https://cdn.azureedge.net/3734/helloworld/elephants-dream.webmvtt"
},
"SoapboxVideos": [
{
"_id": {
"$oid": "60373e34ad2fe9624705f40d"
},
"VideoPaths": null,
"Title": "Testing title",
"TagId": "TESTING",
"TagTypeId": null,
"Thumbnail": null,
"GroupId": "5ffd8d7f7d553920b9608f38",
"VideoImageUrl": null,
"VideoType": null,
"VideoUrls": "https://cdn.azureedge.net/3734/helloworld/elephants-dream.webm",
"ProcessedVideoUrls": null,
"VideoId": null,
"VttUrl": null,
"IsDeleted": false,
"Duration": 0
},
{
"_id": {
"$oid": "603740d4ad2fe9624705f40e"
},
"VideoPaths": null,
"Title": "Testing title",
"TagId": "TESTING",
"TagTypeId": null,
"Thumbnail": null,
"GroupId": "DigitalEvents_5ffd8d7f7d553920b9608f38",
"VideoImageUrl": null,
"VideoType": null,
"VideoUrls": "https://cdn.azureedge.net/3734/helloworld/elephants-dream1.webm",
"ProcessedVideoUrls": null,
"VideoId": null,
"VttUrl": null,
"IsDeleted": false,
"Duration": 0
},
{
"_id": {
"$oid": "603752ce7904007c5cc93e79"
},
"VideoPaths": null,
"Title": "Testing title",
"TagId": "TESTING",
"TagTypeId": null,
"Thumbnail": null,
"GroupId": "DigitalEvents_5ffd8d7f7d553920b9608f38",
"VideoImageUrl": null,
"VideoType": null,
"VideoUrls": "https://cdn.azureedge.net/3734/helloworld/elephants-dream.webm",
"ProcessedVideoUrls": null,
"VideoId": null,
"VttUrl": null,
"IsDeleted": false,
"Duration": 0
}
]
}
]
}]
Since it requires two positional operators, I am following below method. I am trying to update ProcessedVideoUrls, VttUrl inside SoapboxVideos list.
updateResult = await _userCollection.UpdateOneAsync(x => x.Id == updateVideoPath.UserId, // 602cb1627661691f87bb1e6e
Builders<UserModel>.Update.Set("Events.$[event].SoapboxVideos.$[soapbox].ProcessedVideoUrls", updateVideoPath.VideoUrls)
.Set("Events.$[event].SoapboxVideos.$[soapbox].VttUrl", updateVideoPath.VttUrl),
new UpdateOptions
{
ArrayFilters = new List<ArrayFilterDefinition>
{
new BsonDocumentArrayFilterDefinition<BsonDocument>(new BsonDocument("event.Id", updateVideoPath.EventId)), // 5ffd8d7f7d553920b9608f38
new BsonDocumentArrayFilterDefinition<BsonDocument>(new BsonDocument("soapbox.Id", updateVideoPath.Id)) // 603752ce7904007c5cc93e79
}
});
When it get executed, I am not getting any exceptions as such.. Rather I am getting MatchedCount as 1 and ModifiedCount as 0. Please note that the field which I am trying to update defenitly has value, which is not the existing value too.
Any help to understand the issue is appreciated. I am using Mongo driver version number 2.11.6
Following changes in the code resolved the issue
new UpdateOptions
{
ArrayFilters = new List<ArrayFilterDefinition>
{
new BsonDocumentArrayFilterDefinition<BsonDocument>(new BsonDocument("event._id", updateVideoPath.EventId)),
new BsonDocumentArrayFilterDefinition<BsonDocument>(new BsonDocument("soapbox._id", ObjectId.Parse( updateVideoPath.Id)))
}
});
Actual issue was the Soapbox Id type, it is ObjectId and I have used property "soapbox.Id" instead of "soapbox._id". Those changes resolved the issue.
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
I use .Net Framework with WebApi on my Server and Javascript/AngularJs on my Client. I want to transfer an Tree with References to my Client. I found a Way to get it to the Client, i just set PreserveReferencesHandling.Objects at the Newtonsoft Json.
Json looks like this:
{
"$id": "1",
"id": 1,
"revisionNumber": 0,
"name": "Revision 0",
"parentRevisionNode": null,
"nextRevisionNode": null,
"prevRevisionNode": null,
"childRevisionNodes": [
{
"$id": "2",
"id": 2,
"revisionNumber": 0,
"name": "Node 1",
"parentRevisionNode": {
"$ref": "1"
},
"nextRevisionNode": null,
"prevRevisionNode": null,
"childRevisionNodes": [
{
"$id": "3",
"id": 3,
"revisionNumber": 0,
"name": "Node 1.1",
"parentRevisionNode": {
"$ref": "2"
},
"nextRevisionNode": null,
"prevRevisionNode": null,
"childRevisionNodes": null,
"data": {
"$id": "4",
"id": 3,
"revisionNumber": 0,
"text": "Data 1.1",
"parentRevisionNode": {
"$ref": "3"
},
"nextRevisionNode": null
}
},
{
"$id": "5",
"id": 4,
"revisionNumber": 0,
"name": "Node 1.2",
"parentRevisionNode": {
"$ref": "2"
},
"nextRevisionNode": null,
"prevRevisionNode": null,
"childRevisionNodes": null,
"data": {
"$id": "6",
"id": 4,
"revisionNumber": 0,
"text": "Data 1.2",
"parentRevisionNode": {
"$ref": "5"
},
"nextRevisionNode": null
}
}
],
"data": {
"$id": "7",
"id": 2,
"revisionNumber": 0,
"text": "Data 1",
"parentRevisionNode": {
"$ref": "2"
},
"nextRevisionNode": null
}
}
],
"data": {
"$id": "8",
"id": 1,
"revisionNumber": 0,
"text": "Data 0",
"parentRevisionNode": {
"$ref": "1"
},
"nextRevisionNode": null
}
}
I found a function that replaces the $id and $ref with the Object. Thats working fine.
Now i want the get that Object Tree back to the Server. But i get an error with circling references on JS Side. Then i thought i can do the same way back, transform the Object References with $id and $ref.
But Angulars $resource cuts out all the $ attributes...
Anyone a good Idea how to get Data back and forth from/to Server?
Thanks in advance
Greeetings
Ronny Gerndt
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"];
I am trying to parse the following JSon to access the name property. But I am having some difficulty.
{[
{
"trends": [
{
"name": "#penaltypointsforpricks",
"url": "http://twitter.com/search?q=%23penaltypointsforpricks",
"promoted_content": null,
"query": "%23penaltypointsforpricks",
"events": null
},
{
"name": "#sometimesiwishthat",
"url": "http://twitter.com/search?q=%23sometimesiwishthat",
"promoted_content": null,
"query": "%23sometimesiwishthat",
"events": null
},
{
"name": "#1000daysof1d",
"url": "http://twitter.com/search?q=%231000daysof1d",
"promoted_content": null,
"query": "%231000daysof1d",
"events": null
},
{
"name": "#ireland",
"url": "http://twitter.com/search?q=%23ireland",
"promoted_content": null,
"query": "%23ireland",
"events": null
},
{
"name": "#savita",
"url": "http://twitter.com/search?q=%23savita",
"promoted_content": null,
"query": "%23savita",
"events": null
},
{
"name": "Twitter",
"url": "http://twitter.com/search?q=Twitter",
"promoted_content": null,
"query": "Twitter",
"events": null
},
{
"name": "Cork",
"url": "http://twitter.com/search?q=Cork",
"promoted_content": null,
"query": "Cork",
"events": null
},
{
"name": "Facebook",
"url": "http://twitter.com/search?q=Facebook",
"promoted_content": null,
"query": "Facebook",
"events": null
},
{
"name": "Boston",
"url": "http://twitter.com/search?q=Boston",
"promoted_content": null,
"query": "Boston",
"events": null
},
{
"name": "Will",
"url": "http://twitter.com/search?q=Will",
"promoted_content": null,
"query": "Will",
"events": null
}
],
"as_of": "2013-04-18T18:34:45Z",
"created_at": "2013-04-18T18:29:40Z",
"locations": [
{
"name": "Dublin",
"woeid": 560743
}
]
}
]}
I had the following suggestion but it returns a null reference exception during run time.
var twitterObject = JToken.Parse(jsonString);
var trendsArray = twitterObject.Children<JProperty>().FirstOrDefault(x => x.Name == "trends").Value;
foreach (var item in trendsArray.Children())
{
var itemProperties = item.Children<JProperty>();
//you could do a foreach or a linq here depending on what you need to do exactly with the value
var myElement = itemProperties.FirstOrDefault(x => x.Name == "url");
var myElementValue = myElement.Value; ////This is a JValue type
}
Anyone have any suggestions how to parse this json response to get each individual "name"
I was able to get the names using this.
dynamic dynObj = JsonConvert.DeserializeObject(jsonString);
foreach (var trend in dynObj[0].trends)
{
Console.WriteLine(trend.name);
}
It'd probably be better to write classes for the JSON objects if you plan to grab anything more than the name, but I hope this helps.