Looping through multiple JObject levels and gathering information as a string - c#

I'm using the following code to gather Json data from a URL.
var json = new WebClient().DownloadString("http://steamcommunity.com/id/tryhardhusky/inventory/json/753/6");
JObject jo = JObject.Parse(json);
JObject ja = (JObject)jo["rgDescriptions"];
int cCount = 0;
int bCount = 0;
int eCount = 0;
foreach(var x in ja){
// I'm stuck here.
string type = (Object)x["type"];
}
CUAI.sendMessage("I found: " + ja.Count.ToString());
Everything is working well until I get to the foreach statement.
Here is a snippet of the JSON Data.
{
"success": true,
"rgInventory": {
"Blah other stuff"
},
"rgDescriptions": {
"637390365_0": {
"appid": "753",
"background_color": "",
"type": "0RBITALIS Trading Card"
"175240190_0": {
"appid": "753",
"background_color": "",
"type": "Awesomenauts Trading Card"
},
"195930139_0": {
"appid": "753",
"background_color": "",
"type": "CONSORTIUM Emoticon"
}
}
}
I'm wanting to loop through each item in rgDescriptions and get the type data as a string, Then check if it contains either background, emoticon or trading card.
I know I can use the if(type.Contains("background")) to check what the item type is, But I'm having trouble with the foreach loop.
If I use foreach(JObject x in ja) I get a cannot convert type Error.
If I use foreach(Object x in ja) It comes up with a Cannot apply indexing of type object.
This error also happens when I use foreach(var x in ja) and string type = (JObject)x["type"];
Can anyone tell me what I'm doing wrong, Please?

You have some errors in your JSON. Check it with jsonlint.com. I think it should look something like this:
{
"success": true,
"rgInventory": {
"Blah other stuff": ""
},
"rgDescriptions": {
"637390365_0": {
"appid": "753",
"background_color": "",
"type": "0RBITALIS Trading Card"
},
"175240190_0": {
"appid": "753",
"background_color": "",
"type": "Awesomenauts Trading Card"
},
"195930139_0": {
"appid": "753",
"background_color": "",
"type": "CONSORTIUM Emoticon"
}
}
}
You can use the JProperty, JToken and the SelectToken Method to get the type:
var json = new WebClient().DownloadString("http://steamcommunity.com/id/tryhardhusky/inventory/json/753/6");
JObject jo = JObject.Parse(json);
foreach (JProperty x in jo.SelectToken("rgDescriptions"))
{
JToken type = x.Value.SelectToken("type");
string typeStr = type.ToString().ToLower();
if (typeStr.Contains("background"))
{
Console.WriteLine("Contains 'background'");
}
if (typeStr.Contains("emoticon"))
{
Console.WriteLine("Contains 'emoticon'");
}
if (typeStr.Contains("trading card"))
{
Console.WriteLine("Contains 'trading card'");
}
}

Related

Parse nested json and return the values as string[]

Can you help me parse the values in 'realEstateProperties' attribute (ex. serial number and economyType.value). Here is a part of the json file:
{
"Entity1": {
"id": "5f514d20744a1fb",
"realEstateProperties": [
{
"serialNumber": "11",
"cadastralSections": [
{
"id": "5f514dc11a1e3",
"economyType": {
"value": "landRegisterPage.type",
}
}
],
"landRegisterPage": {
"id": "3456",
"landRegisterBook": {
"abbreviation": null
},
"note": "LRP",
"tags": null
},
"propertyTextBlock": null
}
],
"customFields": [],
Here is what I currently have:
public static string[] GetJsonValues(string jsonProperty)
{
testCaseName = "Entity1";
FixtureIncident.Root incObject = new FixtureIncident.Root();
incObject = LoadJSONFile();
JObject incJson = JObject.FromObject(incObject);
var attributes = incJson[testCaseName].ToList<JToken>();
var property = attributes.Find(i => i.ToObject<JProperty>().Name == jsonProperty) as JArray; //returns property=null
string[] Properties = property.ToObject<string[]>();
return Properties;
}
property returns null and I am not sure how to correct it.
I need to save all the realEstateProperties values in a string[].
I found some similar topics but I couldn't adjust my code so I make it works. Thanks in advance for your help.

Access child objects from nested JSON

I have a JSON string, which is srtuctered as per the below.
"total": 5,
"filtered": 5,
"items": [
{
"assignedProducts": [
"antivirus"
],
"cloned": false,
"device_encryption_status_unmanaged": false,
"java_id": "2408cf5b-669c-434e-ac4c-a08d93c40e6a",
"last_activity": "2019-09-20T12:36:22.175Z",
"last_user_id": "5c6bc52305f05316ba18db06",
"heartbeat_utm_name": null,
"group_full_name": null,
"is_adsync_group": false,
"is_caching_proxy": false,
"info": {
"processor_architecture": "x64",
"osMajorVersion": 10,
"computer_name": "INDPC01",
"isServer": false,
"osInstallationType": "Client",
"fqdn": "INDPC01",
"osName": "Windows 10 Pro N",
"id": "4280fcb5-66c9-34e4-cac4-0ad8394ce0a6",
"name": "INDPC01"
},
I am using the following code to get values from a JSON string.
var resultObjects = AllChildren(JObject.Parse(response.Content))
.First(c => c.Type == JTokenType.Array && c.Path.Contains("items"))
.Children<JObject>();
foreach (JObject result in resultObjects)
{
foreach (JProperty property in result.Properties())
{
ListBox1.Items.Add(property.Name.ToString() + " - " + property.Value.ToString());
}
}
}
private static IEnumerable<JToken> AllChildren(JToken json)
{
foreach (var c in json.Children())
{
yield return c;
foreach (var cc in AllChildren(c))
{
yield return cc;
}
}
}
I am able to get all the values for everything within "Items", however I am not sure how to access the child JSON objects, for example the information under "info"
You can access childs using indexer, e.g.:
// ...
foreach (JObject result in resultObjects)
{
var architecture = result["info"]["processor_architecture"].ToString();
// ...
}
Note that it might be an easier approach to convert the JSON to an object, e.g. using JsonConvert, instead using JObject.Parse.

Get chrome bookmarks from json

I want to scrape chrome bookmarks using json object. What I want to do is get all bookmarks from 1 folder. That is the structure of the json:
{
"checksum": "d499848083c2c2e3a38f547da4cbad7c",
"roots": {
"bookmark_bar": {
"children": [ {
"children": [ {
"url": "https://www.example.com/"
}, {
"url": "https://www.another-example.com/"
} ],
"name": "foo",
} ],
"name": "Menu bookmarks",
},
"other": {
"name": "Another bookmarks",
},
"synced": {
"name": "Phone bookmarks",
}
},
"version": 1
}
In this case I want to get urls from folder foo. I am using Json.NET to convert string into object. This code:
string input = File.ReadAllText(bookmarksLocation);
using (StringReader reader = new StringReader(input))
using (JsonReader jsonReader = new JsonTextReader(reader)) {
JsonSerializer serializer = new JsonSerializer();
var o = (JToken)serializer.Deserialize(jsonReader);
var allChildrens = o["roots"]["bookmark_bar"]["children"];
var fooFolder = allChildrens.Where(x => x["name"].ToString() == "foo");
foreach (var item in fooFolder["children"]) {
Console.WriteLine(item["url"].ToString());
}
Console.ReadKey();
}
Is giving me an error:
Cannot apply indexing with [] to an expression of type 'IEnumerable<JToken>'
Can you tell me what I did wrong?
there is 1 loop is missing:
var fooFolder = allChildrens.Where(x => x["name"].ToString() == "foo");
foreach (var folder in fooFolder)
{
foreach (var item in folder["children"])
{
Console.WriteLine(item["url"].ToString());
}
}

Get a value from JSON from c#

i am trying to get a value from a json file using c#. the json file looks more like the below string.
{
"results": [
{
"address_components": [
{
"long_name": "3",
"short_name": "3",
"types": [
"street_number"
]
}
],
"formatted_address": "3, Puppalaguda - Manikonda Main Rd, Sri Laxmi Nagar Colony, Manikonda, Hyderabad, Telangana 500089, India",
"geometry": {
"bounds": {
"northeast": {
"lat": 17.4025788,
"lng": 78.3748307
},
"southwest": {
"lat": 17.4019665,
"lng": 78.3733937
}
},
"location": {
"lat": 17.4023166,
"lng": 78.37417409999999
},
"location_type": "RANGE_INTERPOLATED",
"viewport": {
"northeast": {
"lat": 17.4036216302915,
"lng": 78.37546118029151
},
"southwest": {
"lat": 17.4009236697085,
"lng": 78.3727632197085
}
}
},
"place_id": "EmkzLCBQdXBwYWxhZ3VkYSAtIE1hbmlrb25kYSBNYWluIFJkLCBTcmkgTGF4bWkgTmFnYXIgQ29sb255LCBNYW5pa29uZGEsIEh5ZGVyYWJhZCwgVGVsYW5nYW5hIDUwMDA4OSwgSW5kaWE",
"types": [
"street_address"
]
}
]
}
I am looking for the formatted_address element from the json from C#. I am getting lost in JObject, JArray, JToken. I am trying to use NewtonSoft JSON. Thank you.
Using the LINQ-to-JSON API (JObjects) you can get the formatted address easily using the SelectToken method:
JObject obj = JObject.Parse(json);
string address = (string)obj.SelectToken("results[0].formatted_address");
Console.WriteLine(address);
Fiddle: https://dotnetfiddle.net/Fdvqkl
The easiest way would be to have model objects and then call
var rootObject = JsonConvert.DeserializeObject(jsonString);
With jsonString being your input. Then you can retrieve the formatted_address from the first array element like this like this:
var formattedAddress = rootObject.results[0].formatted_address;
Hope it helps.
using Newtonsoft.Json nuget . and do something like that
static void Main(string[] args)
{
string json = "{'results':[{'SwiftCode':'','City':'','BankName':'Deutsche Bank','Bankkey':'10020030','Bankcountry':'DE'},{'SwiftCode':'','City':'10891 Berlin','BankName':'Commerzbank Berlin (West)','Bankkey':'10040000','Bankcountry':'DE'}]}";
var resultObjects = AllChildren(JObject.Parse(json))
.First(c => c.Type == JTokenType.Array && c.Path.Contains("results"))
.Children<JObject>();
foreach (JObject result in resultObjects)
{
foreach (JProperty property in result.Properties())
{
// do something with the property belonging to result
}
}
}
// recursively yield all children of json
private static IEnumerable<JToken> AllChildren(JToken json)
{
foreach (var c in json.Children())
{
yield return c;
foreach (var cc in AllChildren(c))
{
yield return cc;
}
}
}
change JTokenType.Array to whatever the type u wish , also change the "results" to the property name you wish to extract

Unable to get data from Json Object

I am fetching some data from external Webservice and parsing it to json using Newtonsoft.Json.Linq
like this
JObject o = JObject.Parse(json);
JArray sizes = (JArray) o["data"];
Now the Sizes looks like this
{
[
{
"post_id": "13334556777742_6456",
"message": "messagecomes her",
"attachment": {
"media": [
{
"href": "http://onurl.html",
"alt": "",
"type": "link",
"src": "http://myurl.jpg"
}
],
"name": "come to my name",
"href": "http://mydeeplink.html",
"description": "",
"properties": [],
},
}
]
}
I need to get "src": "http://myurl.jpg"element from this Json array.
I have tried:
foreach (JObject obj in sizes)
{
JArray media = (JArray)obj["attachment"];
foreach (JObject obj1 in media)
{
var src = obj1["src"];
}
}
But it's throwing an error:
Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Newtonsoft.Json.Linq.JArray'.
at this line
JArray media = (JArray)obj["attachment"];
Can any one give me a hand on this?
Try fix line
JArray media = (JArray)(obj["attachment"]);
to
JArray media = (JArray)(obj["attachment"]["media"]);
This is how I handled a scenario that sounds just like yours:
public static IList<Entity> DeserializeJson(JToken inputObject)
{
IList<Entity> deserializedObject = new List<Entity>();
foreach (JToken iListValue in (JArray)inputObject["root"])
{
Entity entity = new Entity();
entity.DeserializeJson(iListValue);
deserializedObject.Add(entity);
}
return deserializedObject;
}
public virtual void DeserializeJson(JToken inputObject)
{
if (inputObject == null || inputObject.Type == JTokenType.Null)
{
return;
}
inputObject = inputObject["entity"];
JToken assertions = inputObject["assertions"];
if (assertionsValue != null && assertionsValue.Type != JTokenType.Null)
{
Assertions assertions = new Assertions();
assertions.DeserializeJson(assertionsValue);
this.Assertions = assertions;
}
// Continue Parsing
}

Categories

Resources