How to extract specific value from this json string using linq - c#

could anyone help me extract the specific value for [downloads][csv][href] out of the following json string please?
{
"#context": "https://cdn.ons.gov.uk/assets/json-ld/context.json",
"alerts": [],
"collection_id": "cmdr",
"dimensions": [
various dimensions here
],
"downloads": {
"csv": {
"href": "https://download.beta.ons.gov.uk/downloads/datasets/regional-gdp-by-year/editions/time-series/versions/4.csv",
"size": "568021"
},
"csvw": {
"href": "ref",
"size": "1903"
},
"xls": {
"href": "ref",
"size": "80768"
}
},
"edition": "time-series",
"id": "5c",
"links": {
"dataset": {
"href": "ref",
"id": "regional-gdp-by-year"
},
"edition": {
"href": "ref",
"id": "time-series"
},
"self": {
"href": "ref"
}
},
"release_date": "2021",
"state": "published",
"usage_notes": [],
"version": 4
}
the current code I am using returns nothing:
var labels = JObject.Parse(observationsJson)["downloads"];
var results = labels.Select(data => new
{
label = (string)data["href"]
});
foreach (var item in results)
{
csvDownloadAddress = item.label;
}
If there is another method rather than using linq then I am open to suggestions.
Sorry if this is a dumb quest, my experience with linq and json is very limited.
thank you for your help.

You have JSON Path, that can be used to select specific element(s) from the JSON string.
see Newtonsoft example, or you can use this JsonPath Nuget package.
The JsonPath Nuget can be used like below,
var input = "$.downloads.csv.href";
var path = JsonPath.Parse(input);
var hrefVal = path.Evaluate(jsonStr);

Related

access value in JSONArray C# UWP

I want to extract the first value in a JSONArray as String. Somehow I have the wrong approach, I get an exception.
How can I improve this?
I think I reach the array fine via myJasonObject["entities"].toArray(), but when I try to do something like getString()["entity"] afterwards, it's marked as error by VS.
I want to be able to store "dax" (the value of "entity"):
Response{
"query": "what about dax",
"topScoringIntent": {
"intent": "StockPrice2",
"score": 0.3969668
},
"intents": [
{
"intent": "StockPrice2",
"score": 0.3969668
},
{
"intent": "None",
"score": 0.372112036
},
],
"entities": [
{
"entity": "dax",
"type": "StockSymbol"
}
]
}
You can get "dax" using following:
JObject obj = JObject.Parse(json);
JArray entities = obj.GetValue("entities") as JArray;
var firstEntity = entities.FirstOrDefault() as JObject;
var entityPropertyValue = entity.GetValue("entity");
var daxString = entityPropertyValue.ToString();

how to make json object in c#?

I have all values from aspx page. now I want to prepare following json values by picking up from the control values of aspx where user has inputted and want to submit to other application in same format.For that below is the example I want to make exact copy as like below.
var tempk = {
"requestTypeCode": "PRE_DETERMINATION",
"billingProvider": {
"npi": "1234567893",
"ein": "111222333",
"payerAssignedProviderId": "XYZ321"
},
"patient": {
"relationshipCode": "01",
"lastName": "Smith",
"firstName": "Bob",
"stateCode": "FL",
"birthDate": "1980-02-12",
"genderCode": "M"
},
"payer": {
"id": "BCBSF"
},
"submitter": {
"id": "123456789",
"lastName": "SUBMITTER"
},
"subscriber": {
"memberId": "JDH001",
"groupName": "ASDF 1-2",
"groupNumber": "12312412"
},
"claimInformation": {
"placeOfServiceCode": "11",
"diagnoses": [
{
"qualifierCode": "ABK",
"code": "J3089"
}
],
"serviceLines": [
{
"procedureCode": "92523",
"quantity": "100",
"amount": "250",
"fromDate": "2016-05-10"
}
]
}
}
Can you assist me how with the C# code will achieve?
You can use Newtonsoft.Json from nuget
http://www.newtonsoft.com/json

How to extract ID from the following JSON Object in C#?

I want to extract all IDs from the below object using c#.
in need of extracting a response value in a visual studio webtest.
The JSON is obtained using extract event.
{
"d": [
{
"__type": "QuestionZoneEditor.Entities.QuestionTag",
"Id": 2080,
"Name": "01",
"Items": [
"1a",
"1b",
"1c",
"1d"
]
},
{
"__type": "QuestionZoneEditor.Entities.QuestionTag",
"Id": 2081,
"Name": "02",
"Items": [
"2a(i)",
"2a(ii)",
"2b",
"2c"
]
},
{
"__type": "QuestionZoneEditor.Entities.QuestionTag",
"Id": 2082,
"Name": "03",
"Items": [
"3a",
"3b",
"3c"
]
}
}
]
}
Deserialize it to JObject after that take all JObject from the JArray and print the Id
var result = JsonConvert.DeserializeObject<JObject>(json);
foreach(JObject obj in result["d"])
{
Console.WriteLine(obj["Id"]);
}
Full example: dotNetFiddle

Deserialize Dynamic Json string using Newtonsoft JSON.NET

I have a JSON string that I'm getting from Facebook API, in which I have a node whose name changes according to its content, for example some time it is 45, or 58 etc.
It could be any number.
I want its value. How to get it?
Example:
{
"data": [
{
"id": "1492292372_10201810786059989",
"created_time": "2014-04-05T09:00:54+0000"
},
{
"id": "1492292372_10201804679827337",
"created_time": "2014-04-04T07:29:07+0000"
},
{
"id": "1492292372_10201804649306574",
"created_time": "2014-04-04T07:10:33+0000"
},
{
"id": "1492292372_10201801316823264",
"created_time": "2014-04-03T18:31:50+0000"
},
{
"id": "1492292372_10201798962284402",
"created_time": "2014-04-03T06:24:47+0000"
},
{
"message_tags": {
"0": [
{
"id": "1492292372",
"name": "Yawar Sohail",
"type": "user",
"offset": 0,
"length": 12
}
],
"15": [
{
"id": "1489845168",
"name": "Zeeshan Anjum",
"type": "user",
"offset": 15,
"length": 13
}
]
},
"id": "1492292372_10201796274777216",
"created_time": "2014-04-02T17:57:05+0000"
},
{
"id": "1492292372_10201794080482360",
"created_time": "2014-04-02T07:26:23+0000"
},
Inside message_tags there are two nodes [0 and 15] they dynamically changes according to their offset values. I want names, type and ids inside these nodes.
You can deserialize your JSON into an ExpandoObject:
var converter = new ExpandoObjectConverter();
dynamic obj = JsonConvert.DeserializeObject<ExpandoObject>(json, converter);
Which dynamically adds members to your object at runtime, and allows you to iterate over them as described in this answer:
foreach (var prop in obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
Console.WriteLine("Name: {0}, Value: {1}",prop.Name, prop.GetValue(obj,null));
}
That way you can iterate over obj.message_tags to get the individual messages, and obtain all their details respectively.

Json nested parameters

I am using data from a Json object to populate a list view. The object has these parameters:
"id": "339150749455906",
"posts": {
"data": [
{
"id": "339150749455906_545370565500589",
"from": {
"category": "Food/beverages",
"name": "Pepsi",
"id": "339150749455906"
},
"story": "Pepsi updated their cover photo.",
"picture": "http://photos-g.ak.fbcdn.net/hphotos-ak-ash3/942740_545370555500590_46289134_s.jpg",
"link": "http://www.facebook.com/photo.php?fbid=545370555500590&set=a.365573920146922.72816.339150749455906&type=1&relevant_count=1",
"icon": "http://static.ak.fbcdn.net/rsrc.php/v2/yz/r/StEh3RhPvjk.gif",
"actions": [
{
"name": "Comment",
"link": "http://www.facebook.com/339150749455906/posts/545370565500589"
},
{
"name": "Like",
"link": "http://www.facebook.com/339150749455906/posts/545370565500589"
}
],
I want to access the link inside the parameter/key "actions". So far I am using:
foreach (var post in postsTaskResult.posts.data)
{
link = new Uri(string.Format("{0}", (string)post["link"]));
}
However, this only brings the link in the "data". How can I access the other 'link' ?
Try this.
var actionLinks = new List<string>();
var actions = post["actions"] as JArray; // if this works then all is well
foreach(var item in actions)
{
actionLinks.Add((string)item["link"]);
}
I think you can also use some fancy Linq with this like
var actionLinks = ((JArray)post["actions"])
.Children<JObject>()
.Select(a => (string)a["link"])
.ToList();
Very un-tested. Just let me know.

Categories

Resources