JSON nested array - c#

Lets say i have the following JSON
{
"data": [
{
"from": {
"name": "aaa bbb",
},
"actions": [
{
"name": "Comment",
"link": "http://...
},
{
"name": "Like",
"link": "http://.."
}
],
},
And i have
JSONObject wallData = helper.Get("/me/feed");
if (wallData != null)
{
var data = wallData.Dictionary["data"];
List<JSONObject> wallPosts = data.Array.ToList<JSONObject>();
}
foreach (Facebook.JSONObject wallItem in wallPosts)
{ ... }
Which stores me whole feed into wallData and 'data' object into wallPosts.
So then i can access the wallItem.Dictionary["from"].Dictionary["name"], and i get "aaa bbb".
But i can't get inside the actions array
The wallItem.Dictionary["actions"].Dictionary["name"] doesn't work.
Any idea

You need to do something like wallItem.Dictionary["actions"][0].Dictionary["name"] because "actions" is an array.

On a different note...its neater if u directly into a class...like this
var jSerializer = new JavaScriptSerializer();
var jsonObject = jSerializer.Deserialize<DataObject>(json);
The DataObject will be a class which emulates ur JSON data in a strongly typed class. Depending on the size of ur Json you will not have to use a lot of strings in your code.

Related

.net core How to get json object using path in string variable

How to get json object using path in string variable,This is the JSON Schema data structure string stored in my database,I tried to convert to json data structure but it didn't work,I want to convert such a string data structure into a json object.
string json = $#"{{
""xcollapse.id"":""xcollapse"",
""xcollapse.el"":202,
""xcollapse.cols.props.cn"":""title"",
""xcollapse.cols.props.desc"":"""",
""xcollapse.cols.props.visible"":-1,
""xcollapse.cols.children.id"":""f272681"",
""xcollapse.cols.children.el"":200,
""xcollapse.cols.children.props"":""{{}}""
}}";
var jObj = JObject.Parse(json);
var result = jObj.ToString();
I would like to get the following results.
{
"xcollapse": {
"id": "xcollapse",
"el": "202",
"cols": [
{
"props": {
"cn": "title",
"desc": "",
"visible": "-1"
},
"children": {
"id": "title",
"el": "",
"props": [
{}
]
}
}
]
}
}
The complete data structure in the database looks like this,I now need to convert to json objects to return to the front end.
{
"xcollapse.id":"xcollapse",
"xcollapse.el":202,
"xcollapse.props":{
},
"xcollapse.styles.visible":-1,
"xcollapse.cols.deletable":false,
"xcollapse.cols.props.cn":"title",
"xcollapse.cols.props.desc":"",
"xcollapse.cols.props.visible":-1,
"xcollapse.cols.styles":null,
"xcollapse.cols.children.id":"f272681",
"xcollapse.cols.children.el":200,
"xcollapse.cols.children.props":{
},
"xcollapse.cols.children.styles.visible":-1,
"xcollapse.cols.children.cols.deletable":false,
"xcollapse.cols.children.cols.props.visible":-1,
"xcollapse.cols.children.cols.styles.span":8,
"xcollapse.cols.children.cols.children.id":"fname",
"xcollapse.cols.children.cols.children.el":100,
"xcollapse.cols.children.cols.children.props.ek":"fbillhead",
"xcollapse.cols.children.cols.children.props.cn":"title",
"xcollapse.cols.children.cols.children.props.group":"",
"xcollapse.cols.children.cols.children.props.fn":"fname",
"xcollapse.cols.children.cols.children.props.pn":"fname",
"xcollapse.cols.children.cols.children.props.desc":"",
"xcollapse.cols.children.cols.children.props.must":"0",
"xcollapse.cols.children.cols.children.props.visible":-1,
"xcollapse.cols.children.cols.children.props.len":"100",
"xcollapse.cols.children.cols.children.props.lock":"0",
"xcollapse.cols.children.cols.children.props.copy":"1",
"xcollapse.cols.children.cols.children.props.defval":"",
"xcollapse.cols.children.cols.children.props.canchange":"0",
"xcollapse.cols.children.cols.children.props.xlsin":"1",
"xcollapse.cols.children.cols.children.props.acl":"1",
"xcollapse.cols.children.cols.children.props.sbm":"0",
"xcollapse.cols.children.cols.children.props.notrace":"1",
"xcollapse.cols.children.cols.children.props.apipn":"sourceType",
"xcollapse.cols.children.cols.children.props.ctlfk":"",
"xcollapse.cols.children.cols.children.props.editmode":"0",
"xcollapse.cols.children.cols.children.props.xsslv":"0",
"xcollapse.cols.children.cols.children.styles.align":"left",
"xcollapse.cols.children.cols.children.styles.width":"",
"xcollapse.cols.children.cols.children.styles.row":2,
"xcollapse.cols.children.cols.children.cols":{},
"xcollapse.cols.children.cols.children.deletable":true,
"xcollapse.cols.children.cols.children.pid":"",
"xcollapse.cols.children.cols.children.seq":1,
"xcollapse.cols.children.cols.seq":1,
"xcollapse.cols.children.deletable":true,
"xcollapse.cols.children.pid":"",
"xcollapse.cols.children.seq":1,
"xcollapse.cols.seq":1,
"xcollapse.deletable":true,
"xcollapse.pid":"",
"xcollapse.seq":1,
}

Reformatting a JSON in C#

I have a JSON response here,
{
"Items": [
{
"Key": {
"timestamp": "2022-11-06T20",
"value": 100.80
}
},
{
"Key": {
"timestamp": "2022-11-07T08",
"value": 100.90
}
}
]
}
That I would like to reformat to this:
{
"Key": [
{
"timestamp": "2019-01-08T20",
"value": 12.44
},
{
"timestamp": "2018-12-12 16:23:00",
"value": 12.45
}
]
}
For all responses, the Key must only be on the top once followed by an array of timestamps and values, and remove the Items parent value completely. I have tried doing this and messing around with the implementation, but I keep receiving multiple different errors. Is this the correct idea to do it or is there a better way to implement this?
JObject obj = JObject.Parse(jsonOutput);
JObject newObj = new JObject();
new JProperty("KEY", new JArray(
.Children<JProperty>()
.Select(j => new JObject(
new JProperty("timestamp", j.Value["timestamp"]),
new JProperty("value", j.Value["value"])
)
)
)
);
jsonOutput = newObj.ToString();
What is the correct way to implement this idea? Thanks!
This can be done very easily by combining
SelectTokens() with a JSONPath wildcard operator for the Items[*] array to select all required JSON objects.
Serialization of an anonymous type object to create the required output structure.
Thus:
var query = obj.SelectTokens("Items[*].Key");
jsonOutput = JsonConvert.SerializeObject(new { Key = query }, Formatting.Indented);
Demo fiddle here.
you can fixed it in one line
jsonOutput = new JObject {new JProperty("Key", ((JArray)JObject.Parse(jsonOutput)
["Items"]).Select(s => s["Key"]))}.ToString();

Transform a JSON object to a JSON array, taking the first level of properties

I've this JSON object
{
"08f4f705-6e14-4781-8241-d04bf2dc6ada": {
"description": "xxxxxxxx",
"note": "yyyyyyyy"
},
"05f4f995-6e14-4567-8241-d04bf2d456ee": {
"description": "aaaaaa",
"note": "bbb"
},
"0675f995-6e14-4567-8241-d4567f2d456z": {
"description": "fffff",
"note": "gggg"
}
}
I need to convert into a JSON array like this:
(the elements should be the content of the first level properties)
[
{
"description": "xxxxxxxx",
"note": "yyyyyyyy"
},
{
"description": "aaaaaa",
"note": "bbb"
},
{
"description": "fffff",
"note": "gggg"
}
]
I can't manipulate the object and I didn't find an appropriate resource to follow. How can I do it?
You can achieve this by deserializing your json string into Dictionary<string, object>:
var obj = JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
After that you extract the values and serialize them back to json:
var newJson = JsonConvert.SerializeObject(obj.Values);

How to use SelectToken to find value in nested dynamic JSON

I can't figure out how to use JToken to get the "Total Income" amount of "325.00".
I have tried quite a few different lines of code but seem to be missing something obvious.
{
"Rows": {
"Row": [
{
"Rows": {
},
"type": "Section",
"group": "Income",
"Summary": {
"ColData": [
{
"value": "Total Income"
},
{
"value": "325.00"
}
]
}
},
{
}
]
}
}
For the specific JSON sample that you have given in your question, you can extract the 325.00 value using SelectToken like this:
var obj = JObject.Parse(json);
var amount = (string)obj.SelectToken("Rows.Row[0].Summary.ColData[1].value");
Fiddle: https://dotnetfiddle.net/WRMAVu
If you want to extract both the label and the amount you can use SelectTokens instead with a wildcard for the ColData index:
var obj = JObject.Parse(json);
var values = obj.SelectTokens("Rows.Row[0].Summary.ColData[*].value")
.Select(t => (string)t)
.ToArray();
Fiddle: https://dotnetfiddle.net/DHZhS2

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