I'm creating wp8 application and have to parse specific json string:
string jsonStr = {
"ver": "1",
"item1": {
"name": "name1",
"desc": "desc1"
},
"item2": {
"name": "name2",
"desc": "desc2"
},
"item3": {
"name": "name3",
"desc": "desc3"
}
}
I need values of key name to get in list, eg. name1, name2, name3. I was trying to find similar situation but with no success.
This works, but I think there will be more elegant way to solve this problem. However you can use it.
var jsonStr = "{\"ver\":\"1\",\"item1\":{\"name\":\"name1\",\"desc\":\"desc1\"},\"item2\":{\"name\":\"name2\",\"desc\":\"desc2\"},\"item3\":{\"name\":\"name3\",\"desc\":\"desc3\"}}";
List<string> names = new List<string>();
JObject jsonObject = JObject.Parse(jsonStr);
jsonObject.Remove("ver");
foreach (JToken jsonRow in jsonObject.Children())
{
foreach (JToken item in jsonRow)
{
foreach (JToken itemProperty in item)
{
var property = itemProperty as JProperty;
if (property != null && property.Name == "name")
{
if (property.Value != null)
{
names.Add(property.Value.ToString());
}
}
}
}
}
Related
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());
}
}
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
I have a JSON file (below). My goal is to, fill a dictionary with unit_ids (f.e. in this JSON unit_ids are: 153470, 153471 and 178903) and corresponding classtype_id (f.e. in this JSON corresponding classtype_id are: CW,CW, null). (unit_ids are uniqe)
So f.e. my dictionary might be: {[153470, CW],[153471, CW],[178903, null]}.
But there is a problem, in my current approach, because of the possibility of: "unit_id":null like f.e. in this file: "178903": null.
Dictionary<string, string> unit_id_translate = new Dictionary<string, string>();
var unitIdsTypes = JObject.Parse(unit_ids_json).SelectTokens("*.['classtype_id']");
var unitIdsNumbers = JObject.Parse(unit_ids_json);
List<String> tempForUID = new List<String>();
List<String> tempForVAL = new List<String>();
foreach (var unitIdType in unitIdsTypes)
{
tempForVAL.Add(unitIdType.ToString());
}
foreach (var unitIdNumber in unitIdsNumbers)
{
foreach (var tmp44 in unitIdNumber)
{
var trimmedNr = unitIdNumber.Cast<JProperty>().Select(o => o.Name);
foreach (var unitIdNr in trimmedNr)
{
tempForUID.Add(unitIdNr);
}
break;
}
}
for (int i = 0; i < tempForUID.Count(); i++)
{
unit_id_translate.Add(tempForUID.ElementAt(i), tempForVAL.ElementAt(i));
}
I need help, because my solution crashes (out of range exception) - there is more unit_ids than classtype_id - because of the null value.
What I can do to fix this ?
{
"153470": {
"topics": {
"en": ""
},
"classtype_id": "CW",
"learning_outcomes": {
"en": ""
},
"course_id": "06-DRSOLI0",
"course_name": {
"en": "Distributed operating systems"
},
"id": 153470,
"teaching_methods": {
"en": ""
}
},
"153471": {
"topics": {
"en": ""
},
"classtype_id": "CW",
"learning_outcomes": {
"en": ""
},
"course_id": "06-DPROLI0",
"course_name": {
"en": "Team project"
},
"id": 153471,
"teaching_methods": {
"en": ""
}
},
"178903": null,
}
You can do this easily with Enumerable.ToDictionary():
var unit_id_translate = JObject.Parse(unit_ids_json)
.Properties()
.ToDictionary(p => p.Name, p => (string)p.Value.SelectToken("classtype_id"));
Then
Console.WriteLine(JsonConvert.SerializeObject(unit_id_translate));
produces {"153470":"CW","153471":"CW","178903":null}.
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'");
}
}
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
}