So I am given a json tree like the one below and I really just need to get the persons first and last names from here but I am having problems parsing the data.
{
"results":[
{
"id":{
"key":"Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Phone.81dd6fef-a2e2-4b08-cfe3-bc7128b43786.Durable.json?api_key=",
"type":"Phone",
"uuid":"81dd6fef-a2e2-4b08-cfe3-bc7128b43786",
"durability":"Durable"
},
"line_type":"Landline",
"belongs_to":[
{
"id":{
"key":"Person.1ffee2ef-cc88-4a1e-87b0-05349571b801.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Person.1ffee2ef-cc88-4a1e-87b0-05349571b801.Durable.json?api_key=",
"type":"Person",
"uuid":"1ffee2ef-cc88-4a1e-87b0-05349571b801",
"durability":"Durable"
},
"type":"Full",
"names":[
{
"salutation":null,
"first_name":"fred",
"middle_name":null,
"last_name":"jones",
"suffix":null,
"valid_for":null
}
],
"age_range":null,
"gender":null,
"locations":[
{
"id":{
"key":"Location.bd4721f0-ba97-4ade-aac1-ed1f16be57ed.Durable",
"url":"https://proapi.whitepages.com/2.1/entity/Location.bd4721f0-ba97-4ade-aac1-ed1f16be57ed.Durable.json?api_key=",
"type":"Location",
"uuid":"bd4721f0-ba97-4ade-aac1-ed1f16be57ed",
"durability":"Durable"
},
"type":"Address",
"valid_for":{
"start":{
"year":2011,
"month":7,
"day":5
},
"stop":null
},
"legal_entities_at":null,
"city":"",
"postal_code":"",
"zip4":null,
"state_code":"",
"country_code":"",
"address":"",
"house":"10",
"street_name":"",
"street_type":"Ave",
"pre_dir":null,
"post_dir":null,
"apt_number":null,
"apt_type":null,
"box_number":null,
"is_receiving_mail":false,
"not_receiving_mail_reason":null,
"usage":null,
"delivery_point":null,
"box_type":null,
"address_type":null,
"lat_long":{
"latitude":,
"longitude",
"accuracy":"Street"
},
"is_deliverable":true,
"standard_address_line1":"",
"standard_address_line2":"",
"standard_address_location":"",
"is_historical":false,
"contact_type":"Home",
"contact_creation_date":1361177323
}
],
The code I have been using so far is:
string url = String.Format("https://proapi.whitepages.com/2.1/phone.json?api_key={0}&phone_number={1}", WhitePagesConstants.ApiKey, number);
using (WebClient webClient = new System.Net.WebClient())
{
WebClient n = new WebClient();
n.Encoding = System.Text.Encoding.UTF8;
var json = n.DownloadString(url);
Dictionary<string, Object> formattedjson = JsonConvert.DeserializeObject<Dictionary<string, Object>>(json);
}
I have been on this for too long and must finish it shortly so I ask please help me traverse this tree. I have never worked with json before and am quite lost on how to do this. The exact info I need is under "belongs_to" -> "names" -> first and last. I've changed some names to protect the innocent.
If all you need is to extract several properties, you can just navigate the path:
dynamic o = JsonConvert.DeserializeObject(json);
Console.WriteLine(o.results[0].belongs_to[0].names[0].first_name);
Console.WriteLine(o.results[0].belongs_to[0].names[0].last_name);
Or, if you prefer string dictionaries over dynamic objects:
JObject j = JsonConvert.DeserializeObject<JObject>(json);
Console.WriteLine(j["results"][0]["belongs_to"][0]["names"][0]["first_name"]);
Console.WriteLine(j["results"][0]["belongs_to"][0]["names"][0]["last_name"]);
P.S. Your JSON is broken. It would have been easier for me to test code if you provided a correct example.
Related
Below is my Requirement-
Actual JSON=
{
"page":2,
"per_page":6,
"total":12,
"total_pages":2
}
I want to make it as below-
[
{
"page":2,
"per_page":6,
"total":12,
"total_pages":2
}
]
It would be great help if someone can provide the best logic to do this in C# (RestSharp)
Basically you can store your json data inside the list.
var json = new
{
name = "john doe",
age = 20
};
var list = new List<dynamic>();
list.Add(json);
Later on, when you serialize your list. It will look like this:
[{"name":"john doe","age":20}]
Hopefully it helps.
Create an empty array and then push json object into that array.
Example :
var obj = { "name":"test", "email":"test#test.com" };
var list = [];
list.push(obj);
Result :
list = [{ "name":"test", "email":"test#test.com" }];
You can use below code, this is working one.
var obj = new { name = "test", email = "test#test.com" };
var list = new List<dynamic>();
list.Add(obj);
Recently, I have been dabbling in reading json data into my C# code with the intent of storing property data in the json file to be loaded at run time. For example, I'd like to make a json file for each datagrid and have each column represented as a unique as a section in the json file; something like this:
[
{
"colWidth": 1,
"rowHeight": 10,
"moreStuff": 20
},
{
"ColWidth": 2,
"rowHeight": 100,
"SecondBAID": 200
},
{
"ColWidth": 3,
"rowHeight": 1000,
"moreStuff": 2000
},
{
"ColWidth": 4,
"rowHeight": 10000,
"moreStuff": 20000,
"someArray: [true, 5, "Column notes"]
},
{
"ColWidth": 5,
"rowHeight": 100000,
"moreStuff": 200000,
"evenMoreStuff":300000
}
]
The code I am currently using to read this file and assign the data is as follows:
public static void LoadJson()
{
string json;
using (StreamReader r = new StreamReader(#"test.json"))
{
json = r.ReadToEnd();
}
dynamic array = JsonConvert.DeserializeObject(json);
var list = new List<MyClass>();
foreach (var section in array)
{
var si = new MyClass();
if (section.Whatever!= null)
{
si.Test1 = section.Whatever;
}
if (section.Whatever2!= null)
{
si.Test2 = section.Whatever2;
}
if (section.Whatever3!= null)
{
si.Test3 = section.Whatever3;
}
if (section.Whatever4!= null)
{
si.Test4 = section.Whatever4;
}
list.Add(si);
}
}
I have a few questions regarding this though...
1) Is there an easier way to filter out null values? Sometimes I want the property of a column to be the default value, and I'd rather not nest dozens of if statements if possible. Is there a way to basically say "If this property doesn't exist in the json section, just ignore it"
Presently I am just iterating through all of the possible properties, doing a simple get/set in the MyClass, and storing the variables (For this example, I use "whatevers" so I don't post hundreds of lines of code; the whatevers represent legitimate fields in the json file.
2) I am currently adding each section of the json file to a dynamic array. How can I achieve this when I want to add an array of properties to the dynamic array? I'd like to change the C# code such that if I have a nested array, it will be added to some sort of multi level list. What is the best way to do this?
I'm using this (Is it possible to have nested array json?) as a reference to nest arrays in the json.
Any advise would be awesome!
I have a problem on data parsing, I am using C# in Visual Studios and I need a parsing algorithm for my json file. This is the structure:
{
"objects": {
"minecraft/sounds/mob/stray/death2.ogg": {
"hash": "d48940aeab2d4068bd157e6810406c882503a813",
"size": 18817
},
"minecraft/sounds/mob/husk/step4.ogg": {
"hash": "70a1c99c314a134027988106a3b61b15389d5f2f",
"size": 9398
},
"minecraft/sounds/entity/rabbit/attack2.ogg": {
"hash": "4b90ff3a9b1486642bc0f15da0045d83a91df82e",
"size
I want to pull "minecraft/sounds/mob/stray/death2.ogg" and "hash" the data.
My C# code:
HttpWebRequest reqobje = WebRequest.Create(assetsurl) as HttpWebRequest;
using (HttpWebResponse response = reqobje.GetResponse() as HttpWebResponse)
{
StreamReader objejsonsr = new StreamReader(objectjson);
jsonVerisi = objejsonsr.ReadToEnd();
}
parser = JObject.Parse(jsonVerisi);
JToken job = parser["objects"];
Since you're using json.net, you can deserialize the string into any object you need. The sample below is an anonymous type with dictionary so you can use the dynamic keys that are coming back:
var result = JsonConvert.DeserializeAnonymousType(jsonVerisi, new { objects =
new Dictionary<string, Dictionary<string, string>>() });
var objects = result.objects; // key/value;
This is one way you can use it (maybe even to map to your own model instead of anonymous types to make it easier to work with):
var objects = result.objects
.Select(m => new
{
Path = m.Key,
Hash = m.Value["hash"],
Size = int.TryParse(m.Value["size"], out var value) ? value : 0,
}).ToList();
var path = objects[0].Path; // Get the path of the first object
So I what I am trying to do is capture/extract specific data from Steams API for dota2 heroes. I am using C# to do this with this method.
https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=2D13D618DA712015812E970165632F02&language=en_us
{
"result": {
"heroes": [
{
"name": "npc_dota_hero_antimage",
"id": 1,
"localized_name": "Anti-Mage"
},
]
}
This is the code I have been trying with:
WebClient c = new WebClient();
var data = c.DownloadString("https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=2D13D618DA712015812E970165632F02&language=en_us");
JObject o = JObject.Parse(data);
string heroname = (string)o["name"];
But it only returns an error saying the value of "heroname" is null.
Any ideas?
o is going to be an object that contains one key: result. o["result"] will in turn contain a key called heroes. o["result"]["heroes"] is an array of objects. So o["result"]["heroes"][0] will be the first item, and o["result"]["heroes"][0]["name"] is the name from the first item.
I would like to make a Linq query in a json string.
little info about what i'm trying to do. At work we have a web based schedule system which don't have a support for windows 8 and windows phone 8 app. That is why I decided to make one. Using HttpClient I get an http string which I then convert to xml then Json. As you can see from the (Link below, the 'TheWholeJsonString.json' file) the property name and JSON object name is not informative and the JSON file is complicated. That is why I decided to extract some of the values from the JSON string and write a totally new JSON file that include the extracted JSON values in a more informative way.
The [tr] array in the original JSON file have several JSON Objects. Inside the 'VeryShorten.json' file in the linked folder you can see the structure of one of those objects (OBS! there is objcet with different structure). The only thing I hide is the Name and E-Mail address of RL ppl.
I also attached 'ShortenVersion.json' which is only a shorten version of the whole json string, just to make it easy to handle.
Json data sample
{
"#class": "odd",
"td": [
{
"#class": "user",
"#onmouseover": "userInfo('149');",
"#onmouseout": "userInfo(0);",
"#onmousemove": "moveSlotInfo();",
"#text": " ",
"a": {
"#href": "Name3#dreamnet.com",
"#text": "Name3"
}
},
.
.
.
In C# if i try the following code (which is not Linq)
var jObject = JObject.Parse(jString); //jString is 'TheWholeJsonString.json' file in the attached link
var jObj = jObject["tbody"]["tr"][8];
var gh = jObj.Value<JToken>("td").Children().First().Value<JToken>("a").Value<string>("#text");
i can get the value of '#text' which is *'Name3'.
However if i try the following code (Linq version):-
var jObject = JObject.Parse(jString);
var jCollection = jObject["tbody"]["tr"].Children();
var test = from userToken in jCollection
where
userToken.Value<JToken>("td")
.Children()
.First()
.Value<JToken>("a")
.Value<string>("#text")
.Contains("Name3")
select (string)userToken["#text"];
foreach (var item in test)
{
var fgh = item.Type;
}
It will break on the first iteration of foreach loop with the following error msg "Cannot access child value on Newtonsoft.Json.Linq.JValue". I really now what is causing the problem, but i don't know how to solve it. The problem is that not every token inside jCollection have a 'td' object and even if the token have 'td' object it is not Always it have token 'a'. You can see this either in the 'TheWholeJsonString.json' or 'ShortVersion.json' files which i attached in the link.
Hope this will explain more info.
So the question is:- Anyone can help to solve this problem?
You can use SelectTokens method. Notice false as second parameter - don't generate error if element is not found.
var jObject = JObject.Parse(jString);
var trList = jObject["tbody"]["tr"];
string[] names = trList.SelectMany(tr => tr.SelectTokens("td[0].a.#text", false))
.Select(t => t.Value<string>())
.ToArray();
You can easily query with LINQ like this
considering this JSON
{
"items": [
{
"id": "10",
"name": "one"
},
{
"id": "12",
"name": "two"
}
]
}
putting it in a variable called json like this,
JObject json = JObject.Parse("{'items':[{'id':'10','name':'one'},{'id':'12','name':'two'}]}");
you can select all ids from the items where name is "one" using the following LINQ query
var Ids =
from item in json["items"]
where (string)item["name"] == "one"
select item["id"];