I am trying to parse JSON data from Instagram API and I am having problem with parsing the child elements. For example, one Instagram response looks like this:
{
"pagination": {
"next_url": "https://api.instagram.com/v1/users/273112457/followed-by?access_token=1941825738.97584da.3242609045494207883c900cbbab04b8&cursor=1439090845443",
"next_cursor": "1439090845443"
},
"meta": {
"code": 200
},
"data": [
{
"username": "ohdyxl",
"profile_picture": "https://igcdn-photos-e-a.akamaihd.net/hphotos-ak-xfp1/t51.2885-19/11093019_661322517306044_2019954676_a.jpg",
"id": "1393044864",
"full_name": "只有你和我知道"
},
{
"username": "dpetalco_florist",
"profile_picture": "https://igcdn-photos-a-a.akamaihd.net/hphotos-ak-xtf1/t51.2885-19/11192809_930052080349888_1420093998_a.jpg",
"id": "1098934333",
"full_name": "D'petalco florist"
}
]
}
My code is the following:
dynamic d = JObject.Parse(response);
foreach (var result in d["data"])
{
string userName = (string)result["username"];
list.Add(userName);
}
This part works perfectly, however when I try to extract pagination, I get a child error access error.
My code is the following:
foreach (var res in d["pagination"])
{
string nexturl = (string)res["next_url"];
string nextcursor = (string)res["next_cursor"];
}
How can I extract the next_url and next_curosr from "pagination" in C#? Thanks.
Unlike data property value, pagination property value is not an array so you don't need foreach loop here :
var res = d["pagination"];
string nexturl = (string)res["next_url"];
string nextcursor = (string)res["next_cursor"];
or without using intermediate variable res :
string nexturl = (string)d["pagination"]["next_url"];
string nextcursor = (string)d["pagination"]["next_cursor"];
Related
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,
}
How can i acces the first item id?
using (var http = new HttpClient())
{
var res = JArray.Parse(await http.GetStringAsync("http://api.champion.gg/champion/Gragas?api_key=????").ConfigureAwait(false));
^^^^^^ // Also tried with JObject instead of JArray, both don't work
var champion = (Uri.EscapeUriString(res[0]["items"][0]["mostGames"][0]["items"][0]["id"].ToString()));
Console.WriteLine(champion); // ^ [0] here because the JSON starts with an [
}
Example JSON result (made it smaller because the original JSON is over 21500 characters, made sure its valid with https://jsonlint.com, here is the original JSON response: https://hastebin.com/sacikozano.json)
[{
"key": "Gragas",
"role": "Jungle",
"overallPosition": {
"change": 1,
"position": 13
},
"items": {
"mostGames": {
"items": [{
"id": 1402,
"name": "Enchantment: Runic Echoes"
},
{
"id": 3158,
"name": "Ionian Boots of Lucidity"
},
{
"id": 3025,
"name": "Iceborn Gauntlet"
},
{
"id": 3065,
"name": "Spirit Visage"
},
{
"id": 3742,
"name": "Dead Man's Plate"
},
{
"id": 3026,
"name": "Guardian Angel"
}
],
"winPercent": 50.45,
"games": 300
}
}
}]
With JArray i get the following error: Accessed JObject values with invalid key value: 0. Object property name expected.
With JObject i get the following error: Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path '', line 1, position 1.
Thanks in advance, i hope i explained it well
It should be:
var champion = (Uri.EscapeUriString(res[0]["items"]["mostGames"]["items"][0]["id"].ToString()));
The outermost "items" property has a single object as its value, not an array, so [0] is not needed in ["items"][0]. Similarly "mostGames" has a single object value so the [0] is not needed in ["mostGames"][0].
Sample fiddle.
Note that if "items" is sometimes an array of objects, but sometimes is a single object instead of an array of one object, you can introduce the following extension method:
public static class JsonExtensions
{
public static IEnumerable<JToken> AsArray(this JToken item)
{
if (item is JArray)
return (JArray)item;
return new[] { item };
}
}
And do:
var champion = (Uri.EscapeUriString(res[0]["items"].AsArray().First()["mostGames"]["items"][0]["id"].ToString()));
I have a JSON object that looks like this
{
"totalCount": 2,
"students": [{
"name": "abc",
"data": {
"Maths": 20,
"Science": 25
},
"score": 10.0
},
{
"name": "xyz",
"data": {
"Maths": 44,
"Science": 12
},
"score": 11.0
}]
}
I want to deserialize this JSON object to an IEnumerable<String> that contains all the names.
I want -
private IEnumerable<String> GetAllNames(string json) to return ["abc","xyz"]
This is just sample data (and not homework!!). Any advice on how to achieve this would be appreciated. I'm using Newtonsoft library but haven't been able to do this effectively yet. I do not want to iterate through the objects and construct the list myself, any direct way of doing this?
EDIT -
This is what I'm doing currently
var studentList = new List<string>();
var json = JsonConvert.DeserializeObject<dynamic>(jsonString);
foreach (var data in json.students)
{
catalogsList.Add(data.name.toString());
}
return catalogsList;
Try this:
private IEnumerable<string> GetAllNames(string json)
{
JObject jo = JObject.Parse(json);
return jo["students"].Select(s => s["name"].ToString());
}
i have json in object.
{
"data": [
{
"name": "Diljeet Jamwal",
"uid": 553042280,
"pic_square": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash4/274654_553042280_2105727599_q.jpg"
}, {
"name": "Jatinder Sharma",
"uid": 553042280,
"pic_square": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash4/274654_553042280_2105727599_q.jpg"
}]}
i want to show this in list in C#, how to do.
foreach (string data in yourlist)
{
console.WriteLine(data);
}
Of course do the parsing job to fill your list before ;)
You can try Newtonsoft.Json library http://nuget.org/packages/newtonsoft.json/
Example:
String yourdata = "..." // your JSON response
JObject json = JObject.Parse(yourdata);
after this, you can access your data:
String name = json["data"][0]["name"] //it should be Diljeet Jamwal
thanks to all, i have done this
dynamic array = JsonConvert.DeserializeObject(result.ToString());
foreach (var item in array)
{
foreach (var name in item["data"])
{
Response.Write(name["name"]);
}
}
using this
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.