Relatively newbie here with a little question. I been extracting a json string that looks like this (in this case it is a modified return from Facebook oauth2.
{"id":"555555555555555","name":"Monkey
Man","last_name":"Man","first_name":"Monkey","email":"test\u0040someaccount.com","location":{"id":"555555555555555","name":"Jungle,
North
Carolina"},"gender":"male","work":[{"employer":{"id":"555555555555555","name":"Big
Boss makes me work"}:"projects":{"current":"doing stuff",
"previous":"other
stuff"},"location":{"id":"555555555555555","name":"Jungle, North
Carolina"},"position":{"id":"555555555555555","name":"IT
monkey"},"start_date":"2010-09"}],"picture":"http://profile.ak.fbcdn.net/static-ak/rsrc.php/v1/yo/r/5555555-555.gif"}
Well I am able to extract everything to a the dictionary by using the following code
JavaScriptSerializer ser = new JavaScriptSerializer();
Dictionary<string, object> dict = ser.Deserialize<Dictionary<string,object>>(json);
I then extract the data as following from the dictionary and store them in an object called contact which is pretty much just a collection of strings.
if (d.ContainsKey("email"))
{
c.email = d["email"].ToString();
}
else
c.email = "";
I did it this way as I was not gaurenteed the information fields will all be there.
If there is an object set in the value such as with the address I use a modified code (thanks to the guy who showed me how to do that) like following.
c.location = (d["location"] as Dictionary<string, object>)["name"].ToString();
Now come the difficult part that I am stuck on.
I am trying to extract the employer name "Big Boss makes me work" from the following part of the string...
"work":[{"employer":{"id":"555555555555555","name":"Big Boss makes me
work"}:"projects":{"current":"doing stuff", "previous":"other
stuff"},"location":{"id":"555555555555555","name":"Jungle, North
Carolina"},"position":{"id":"555555555555555","name":"IT
monkey"},"start_date":"2010-09"}]
It is storing the data down within an array inside of other objects and I have no idea how to get to the information to extract it, or even how to extract information like this from live oauth2...
"addresses": { "personal": { "street": null, "street_2": null, "city":
"Jungle", "state": "NC", "postal_code": "28677", "region": "United
States" }, "business": { "street": "Tree Street", "street_2": null,
"city": "Jungle", "state": "NC", "postal_code": "28677", "region":
"United States" } }
As you can see this goes three levels deep so my (d["location"] as Dictionary)["name"].ToString(); is pretty useless here. How would you go about getting say the street name from this?
I hope my questions aren't too vague or random. I just need some advice on properly extracting data from the dictionary objects. The ways I come up with involve editing the json string and that causes alsorts of problems as I just don't understand the dictionary object well enough to figure this out on my own
Thanks
Running your JSON through jsonlint.com (and correcting it slightly), it looks like this formatted:
{
"id": "555555555555555",
"name": "Monkey Man",
"last_name": "Man",
"first_name": "Monkey",
"email": "test#someaccount.com",
"location": {
"id": "555555555555555",
"name": "Jungle, North Carolina"
},
"gender": "male",
"work": [
{
"employer": {
"id": "555555555555555",
"name": "Big Boss makes me work"
},
"projects": {
"current": "doing stuff",
"previous": "other stuff"
},
"location": {
"id": "555555555555555",
"name": "Jungle, North Carolina"
},
"position": {
"id": "555555555555555",
"name": "IT monkey"
},
"start_date": "2010-09"
}
],
"picture": "http://profile.ak.fbcdn.net/static-ak/rsrc.php/v1/yo/r/5555555-555.gif"
}
Your JSON data in this case just isn't really suitable to be serialized to a straightforward Dictionary object, so that's not really the way to go here.
The easier way to do is to create a C# class that has defined properties the same as the Javascript object you're de-serializaing. Then, deserialize the JSON as that object and you should be able to access the ""Big Boss makes me work" value should be at objectFromJson.work[0].employer.name .
Related
How to introduce the "attributes" level into JSON text below? I'm using a C# dataset populated from SQL server with SerializeObject from Newtonsoft.json.
This is for submitting data to ESRI batch geocoder, as described here.
The format their REST service expects looks like this
{
"records": [
{
"attributes": {
"OBJECTID": 1,
"Address": "4550 Cobb Parkway North NW",
"City": "Acworth",
"Region": "GA"
}
},
{
"attributes": {
"OBJECTID": 2,
"Address": "2450 Old Milton Parkway",
"City": "Alpharetta",
"Region": "GA"
}
}
]
}
The format my C# script creates looks like this (missing the "attributes" level.)
{
"records": [
{
"OBJECTID": 1,
"address": "4550 Cobb Parkway North NW",
"city": "Acworth",
"state": "GA",
"zip": 30101.0
},
{
"OBJECTID": 2,
"address": "2450 Old Milton Parkway",
"city": "Alpharetta",
"state": "GA",
"zip": 30009.0
}
]
}
I've read thru json.net documentation and wonder if the JsonConverter class could be helpful. Candidly, I'm at loss for how to resolve this. First time user of Json.net, relative newbie with C#
Here is the C# code used to this point:
SQLStatement = "select OBJECTID, Address, City, Region, Postal from MyAddresses";
SqlDataAdapter geoA = new SqlDataAdapter(SQLStatement, GEOconn);
DataSet GeoDS = new DataSet();
geoA.Fill(GeoDS, "records");
string geoAJSON = JsonConvert.SerializeObject(GeoDS);
Console.WriteLine("{0}", geoAJSON);
You can wrap your rows in another object with an "attributes" property using Json.Net's LINQ-to-JSON API.
In your code, replace this line:
string geoAJSON = JsonConvert.SerializeObject(GeoDS);
with this:
var obj = JObject.FromObject(GeoDS);
obj["records"] = new JArray(
obj["records"].Select(jo => new JObject(new JProperty("attributes", jo)))
);
string geoAJSON = obj.ToString();
Working demo here: https://dotnetfiddle.net/nryw27
Aside: based on your JSON it looks like you are storing postal codes in your database as decimals. Don't do that. They may look like numbers, but you should store them as strings. Postal codes in the US can have leading zeros, which will get dropped when you treat them as numbers. Some international postal codes can contain letters, so a numeric type won't even work in that case.
I'm scraping the internet, therefore, the JSON I'm analyzing will be completely different on each webpage. In a nutshell, though, I'm looking to find the author's name.
I'm currently using:
dynamic results = JsonConvert.DeserializeObject(value);
string Author = results.Author;
The problem is, two pages are never the same.
This is an example of two different web pages, with schema which I will find and deserialize & find the author's name.
Example 1:
{
"#context": "https://schema.org",
"#type": "BookSeries",
"author": {
"#type": "Person",
"givenName": "Douglas",
"familyName": "Adams",
"additionalName": "Noel",
"birthDate": "1952-03-11",
"birthPlace": {
"#type": "Place",
"address": "Cambridge, Cambridgeshire, England"
}
}
}
Example 2:
{
"#context": "https://schema.org",
"#type": "WebPage",
"name": "Lecture 12: Graphs, networks, incidence matrices",
"author": "James Beckett",
"description": "These video lectures of Professor Gilbert Strang teaching 18.06 were recorded in Fall 1999 and do not correspond precisely to the current edition of the textbook.",
"publisher": {
"#type": "CollegeOrUniversity",
"name": "MIT OpenCourseWare"
},
"license": "http://creativecommons.org/licenses/by-nc-sa/3.0/us/deed.en_US"
}
Is there a way of truly being dynamic, and finding said values within a JSON string, no matter how they're formatted? With static JSON it's very simple, however, like this - I have absolutely no clue because you can't turn the JSON into C# classes, because they'll always be different.
Any help would be appreciated!
I have an array of complex JSON objects with embedded arrays of JSON objects. By way of an example, one JSON object might look like...
{
"shopID": "12194",
"name": "Shop Name",
"timeZone": "US\/Eastern",
"timeStamp": "2020-11-30T13:25:13+00:00",
"Contact": {
"contactID": "90",
"Addresses": [
"ContactAddress": {
"address1": "123 Some Street",
"address2": "",
"city": "A city",
"state": "A state",
"zip": "12345",
"country": "United States",
"countryCode": "US"
}
],
"Emails": "",
"Websites": {
"ContactWebsite": {
"url": "www.companyname.com"
}
}
},
"TaxCategory": {
"taxCategoryID": "2",
"isTaxInclusive": "false",
"tax1Name": "Tax region name",
"tax1Rate": "0.07"
}
}
I cannot modify the above format... I am calling a public API that is returning this as a response.
Assuming that the corresponding table schema has been created in Google BigQuery, how do I simply insert this JSON as a row in to the table?
My code looks like this...
bqc = BigQueryClient.Create("a-project-id");
var trShops = new TableReference()
{
ProjectId = "a-project-id",
DatasetId = "a-dataset-name",
TableId = "Shops"
};
# Call to my API data source that returns a JSON array of Shops...
content = await _lsrApiHelper.GetRawDataAsync(uri, currentOffset, _apiLimit);
# After call to API I deserialize the JSON response...
response = JsonSerializer.Deserialize<ShopResponseRoot>(content);
# Then I want loop through Shops in the List<ShopResponse> and insert them into BigQuery...
foreach (ShopResponse shop in response.Shop)
{
var newRow = new BigQueryInsertRow();
newRow.InsertId = "shopID";
newRow.Add(shop); # This is where I am struggling
bqc.InsertRow(trShops, newRow);
}
I am struggling with working out how to use a JSON or C# object to populate the data that I want inserting into BigQuery.
Any and all guidance greatly appreciated.
I want to deserialize a json that I get as result of a REST query (the json string can not be changed) to a dictionary type.
The json string looks something like this:
{
"collection": {
"useful": true
"attributes": {
"ObjectID": "ObjectID",
"Name": "Name",
"FirstID": "FirstID",
"LastID": "LastID",
"Count": "5",
},
"Type": "Polyline",
"features": [{
"attributes": {
"length": 0.10879009704943393
"time": 0.3822371137674949,
"text": "some text",
"ABC": -2209161600000,
"Type": "SomeType"
}
}]
}
}
I create boolean property for 'useful' and integer for 'count' etc. but I have a problem with the 'attributes'. As you can see, in each section (and per result) I get different 'attributes'.
I need to deserialize them into some generic collection like dictionary or list of KeyValuePair. the problem is, as stated in msdn (here - http://msdn.microsoft.com/en-us/library/bb412170.aspx) "Dictionaries are not a way to work directly with JSON".
How can I do it if so?
My application is silverlight 5, .Net 4, VS 2010.
Thanks in advance!
I'm having a few problems trying to consume my JSON Data from a web URL and put it into my Class Array.
My class looks something like this;
public class User
{
String Name;
String Serial;
String Email;
}
Where my JSON data looks like
{ "name": "cname", "value": [ "Joe Bloggs"] },
{ "name": "serialnumber", "value": [ "231212312" ] },
{ "name": "gender", "value": [ "male" ] },
{ "name": "email", "value": [ "jbloggs#domain.com" ] },
I want to pop this into a User Class Array so that it would be somthing like
User myUsers[] = new User[100];
I have the data downloaded using a StreamReader, but I'm lost as to where to start. I've tried out DataContractJsonSerializer and a few others but can't find any basic guides on the web where to start.
I should note that I want to only grab the values listed in the class and not extras such as Gender etc.
If someone could provide a basic sample of both the class and the program implementation to read the data that would be great.
Thanks,
CM888.
I Highly Reccomend looking into this library:
Json.NET
It has many great features, but the best is that it's designed to mimic LINQ to XML. You can use it very similarly.
Using this library you could parse your json into objects and work with them & linq queries to build up your user array.
To expand on my comment above: (Unrelated to question or answer)
What i meant was i was curious why your JSON wasn't strctured like this:
[
{"cname": "Joe Bloggs", "serialnumber": "231313213", "gender": "male", "email": "jbloggs#domain.com"},
{"cname": "Another Dude", "serialnumber": "345345345", "gender": "male", "email": "another#dude.com"}
]