JArrary find value from key - c#

I have a long json string that I get from reddit which looks like: this. Once I download and parse the string, I am looking for two parts, "fallback_url" and "thumbnail". The thing is that depending on the time that the reddit post was uploaded the format of the json string can vary so those parts can be in different spots. What I want to do is look through the objects and arrays in the JArray to find the value of "fallback_url" and "thumbnail".
I am trying to use Newtonsoft, but I am not very familiar with it, and when I try the following I get an error:
var data = JArray.Parse(json);
string path = data.Value<string>("fallback_url")?? data.Value<string>("url_overridden_by_dest");
System.ArgumentException: Accessed JArray values with invalid key value: "fallback_url". Int32 array index expected.
Clearly, I'm either using the function wrong or it's not the right function to use. I've tried looking online for answers, but all the examples I found directly referenced the structure of the json to find a value from a key, which I can't do.

Related

How do I convert a JToken to nested list of floats?

I am trying to read in a JSON file using C# consisting of three fields: "name" and "ID", both strings, and "bitmask", which was written out from Python in the nested list format
[[0.0, 0.0], [1.0, 1.0], ...].
Reading the file and accessing the string fields is no problem, but I haven't been able to crack the "bitmask" field. Ultimately I want to be able to put the fields into a dictionary to process into a database later.
I am new to C#, so my approaches have been a bit naive. I attempted to cast it as a List<List<float>> with no luck, as it appears you have to add each sublist iteratively. Is what I am trying to do even possible in C#? Here is my basic read-in code (taken from another extremely helpful post!).
I have access to the Python code that wrote out the JSONs, so if there is a different format for the lists that would make it possible to read in, I can re-process them.
using (StreamReader file = File.OpenText(#"C:\Users...\data2.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
JObject o2 = (JObject)JToken.ReadFrom(reader);
string n = (string)o2.SelectToken("name");
Console.WriteLine("Name field from JSON: {0}", n);
Console.ReadKey();
}
Casting a JToken to a List<List<float>> will not work because JToken only has explicit conversion operators for simple values like string, int, bool, double, etc. (See here for the full list.) To convert a complex object you should use the ToObject method instead:
var bitmask = o2["bitmask"].ToObject<List<List<float>>>();

Json.net, deserialize dates out of range

I'm having trouble deserializing dates with Newtonsoft.Json.
I have a class in C#, and complex data types in postgresql. With the row_to_json function of postgresql I have lot of the work done retriving data from database.
Everything works fine, then, when I have an infinity date, I got this error:
{"Could not convert string to DateTime: -infinity. Path 'valid_from', line 1, position 101."}
The code line I use is:
JsonConvert.PopulateObject(l[icont], myclass);
Where l is a list of json strings, icont is a counter and myclass is an instance of my class.
The closest documentation I found to my problem is here, where this problem is considered a bug: https://bugzilla.xamarin.com/show_bug.cgi?id=22955
I have few workarounds in mind:
Use strings for dates in my c# class. I don't like this :-/
Force the postgresql function to return special dates, like 01/01/1800 and 01/01/2200 and manage them. This can be OK because it is not storical data, but it is not... elegant.
How can I workaround this and keep infinity values in db?

The type string is expected but a type integer was received with value 0

I am working on Marketing APIs. I want to hit this Api to get Estimate of Target Audiences, basically how much users will be able to see my ad.
"https://graph.facebook.com/v2.2/{adaccountid}/reachestimate"
I am getting the response until I pass this parameter "flexible_spec". Whenever I pass this parameter I get this response "The type string is expected but a type integer was received with value 0". I searched for it but no solution was there.
I will show you what I tried until now:
1)"https://graph.facebook.com/v2.2//{adaccountid}/reachestimate? targeting_spec={"geo_locations":{"countries": ["IN"]},"flexible_spec":{"interests":["6006289279425"]}}
2) "https://graph.facebook.com/v2.2//{adaccountid}/reachestimate? targeting_spec={"geo_locations":{"countries": ["IN"]},"flexible_spec":{"interests":["Movies"]}}
3)"https://graph.facebook.com/v2.2//{adaccountid}/reachestimate? targeting_spec={"geo_locations":{"countries": ["IN"]},"flexible_spec":{"interests":["id":"6006289279425","name":"Movies"]}}
I have tried sending an array of ids in flexible spec interests , array of name's in flexible_spec interests and I have also tried sending list<interests> in it. But no luck.
I searched alot about this error. Then i came to know about my mistake i am doing in this API. We can specify interests fields in two types:
1) targeting_spec={"geo_locations":{"countries":"IN"]},"flexible_spec":[{"interests":["6006289279425"]}]}
2) targeting_spec={"geo_locations":{"countries": ["IN"]},"interests":["6006289279425","46345343534"]}
first one passing interests array in flexible_spec array.
second one passing interests as an array object but not in flexible_spec.
This helped me . I am posting this answer because it might help you too in the same situation.
Thanks.

Linq2Twitter Get media entities System.Collections.Generic.List C#

Hi all here comes a noob question,
i am trying around with twitter library "linq2twitter" in C#.
I would like to get the content from :
System.Collections.Generic.List <.LinqToTwitter.MediaEntity.>
My attempt is simple:
public string[] MediaContent;
MediaContent = tweet.Entities.MediaEntities.ToArray()
I tried to convert it into an string[] array with the .ToArray() function but i am getting an the error "conversion from Type LinqToTwitter.MediaEntity[] in string[] is not possible"
I guess there is a better way to get the data from this Type of List ?
Can someone give me a tip?
thx,
Fid
You could use the technique in thorkia's comment to obtain one of the string properties of MediaEntity, but it's not clear that's what you want. Here's how to convert the List to a MediaEntity[]:
public MediaEntity[] MediaContent;
MediaContent = tweet.Entities.MediaEntities.ToArray()
Here, all I did was change the array type from string[] to MediaEntity[].

Json Converter not recognising null attributes and throwing exceptions

Say I have a sample Json format string as
string per1 = #"[{""Email"":""AAA"",""mj_campaign_id"":""22"",""mj_contact_id"":""PPP"",""customcampaign"":""AAA"",""blocked"":""22"",""hard_bounce"":""PPP"",""blocked"":""22"",""hard_bounce"":""PPP""},"
+ #"{""Email"":""BBB"",""mj_campaign_id"":""25"",""mj_contact_id"":""QQQ"",""customcampaign"":""AAA"",""blocked"":""22"",""hard_bounce"":""PPP"",""blocked"":""22""},"
+ #"{""Email"":""CCC"",""mj_campaign_id"":""38"",""mj_contact_id"":""RRR"",""customcampaign"":""AAA"",""blocked"":""22"",""hard_bounce"":""PPP""}]";
I am trying to deserialize it using
var result = JsonConvert.DeserializeObject(per1);
Its working fine as long as all the rows of the string has values for the following attributes Email, mj_campaign_id, mj_contact_id, customcampaign, blocked, hard_bounce, error_related_to, error. But when I skip some sttribute values in some rows its throwing an error saying
Can not add Newtonsoft.Json.Linq.JValue to Newtonsoft.Json.Linq.JObject.
Any help would be appreciated. Thanks
Your error is because you are not assigning a value to an object, which you need to do. If you remove the value, at least add an empty string.
THAT SAID!
Herein lies the danger of manually building JSON strings. You should always avoid it if you can. If you are reading from a web page, that web page should serialize the payload for you, and then you should deserialize it with whatever you are using to pull in the payload (controller, restful service, etc). The beauty of .NET is that it handles all of this plumbing for you and you really are going to run into painful issues if you try to reinvent the .NET wheel

Categories

Resources