Youtube Data v3 Api, Get Request sort - c#

Hey everyone i'm trying to use the v3 Data Youtube API, already have the Request itself and the response looks like this
{
"items": [
{
"snippet": {
"publishedAt": "2016-12-07T16:04:40.472Z",
"displayMessage": "a"
}
}
]
}
The Problem is that i only want the last Comment and not the whole 200(cant be set lower) my first Idea was to Save the whole Response and Compare it to the next one so i know whats new, but that wont really work out

Ok, so from the comments, I gather you are talking about the Live Streaming API.
What you get back are messages, not comments. And yes, as the doc says, "Acceptable values are 200 to 2000, inclusive. The default value is 500." So, you could get the whole 200, and then sort on the timestamp to get the latest message.
How to do that?
As you are doing this in C#, once you have the json string, you need to use some library such as Json.NET. Once you add a NuGet package reference to this, you will need
using Newtonsoft.Json.Linq;
and say your json string is
var json = #"{
""items"": [
{
""snippet"": {
""publishedAt"": ""2016-12-07T16:04:40.472Z"",
""displayMessage"": ""a""
}
}
,
{
""snippet"": {
""publishedAt"": ""2016-12-12T16:04:40.472Z"",
""displayMessage"": ""b""
}
}
]
}";
Then, as described in this documentation, use JObject.Parse to use LINQ to JSON.
var parsedJson = JObject.Parse(json);
JArray items = parsedJson.SelectToken("items") as JArray;
var sortedItems = items.OrderByDescending(item => item["snippet"]["publishedAt"]);
// sortedItems.First() will give you the item with the newest timestamp
Have put all of this at https://dotnetfiddle.net/ubQAZV.
Alternately, you can use JsonConvert if you prefer to deserialize to strongly-typed code.
More about it here.

Related

How do I parse the below dynamic JSON

I have a json which is badly formatted. I want to take out the status and order id from that json. Tried JSON parsing with object, but did not get the result. Please help,
My Json,
{
"formname": [
"Sale_Order_API",
{
"operation": [
"add",
{
"values": {
"Order_ID": "1250",
"Email": "xyz#yws.in",
"Order_Value": "100",
"Restaurant_Name": "HiTech",
"Order_Date": "13-Aug-2019",
},
"status": "Failure, Duplicate values found for
'Order ID'"
}
]
}
]
}
Please help.
This is my first question , please ignore mistakes.
I have tried something like this, But not able to get the inner values
dynamic resultdata = json_serializer.DeserializeObject(postData);
If I understand you correctly, you want to deserialize this JSON. On 'http://json2csharp.com/#' you can generate a C # class from your JSON. Or right by your own. There are plenty of tutorials on the Internet. In case your class, where you give the values of the Json, is called 'JSONResult', you could access the values as follows
var resultdata = JsonConvert.DeserializeObject<JSONResult>(postData);
JSONResult outPut = resultdata;
Console.WriteLine(outPut.formname[0]);
But the longer I look at the format of your JSON, the more confused I get. Where did you get the JSON from? From an API?

c# Json reading child object

I am trying to read child elements in the Json object below. Below is the Json example. I want to read RecommendedCount and TotalReviewCount in testdata1, testdata2 and testdata3.
{
"HasErrors": false,
"Includes": {
"test ": {
"testdata1": {
"ReviewStatistics": {
"RecommendedCount": 0,
"TotalReviewCount": 2
}
},
"testdata2": {
"ReviewStatistics": {
"RecommendedCount": 0,
"TotalReviewCount": 2
}
},
"testdata3": {
"ReviewStatistics": {
"RecommendedCount": 0,
"TotalReviewCount": 2
}
}
}
}
}
I tried the code below.
RecommendedCount = apiResponse.Includes.Products[key].ReviewStatistics.RecommendedCount,
TotalReviewCount = apiResponse.Includes.Products[key].ReviewStatistics.TotalReviewCount
But this is very slow as the Json response has more than 1000 lines so it is taking time. I want to know is there any linq i can use to find the relevant data or any other methods i can use?
Thanks in advance.
var jObj = (JObject)JsonConvert.DeserializeObject(rawJson);
foreach (var child in jObj["test"].Children())
{
}
The above is the deserialize code i am trying to use but getting Object reference not set to an instance of an object. error
My solution:
JObject obj = JObject.Parse(jsonString);
var recList= obj.SelectTokens("$..ReviewStatistics.RecommendedCount").ToList();
var totalList= obj.SelectTokens("$..ReviewStatistics.TotalReviewCount").ToList();
Then you can get the data that you want. For example, if you want RecommendedCount from testdata2, you do like this
var dataYouWant = (int)recList[1];
References:
http://www.newtonsoft.com/json/help/html/LINQtoJSON.htm
Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)
https://msdn.microsoft.com/en-us/library/cc197957(v=vs.95).aspx
If there is anything wrong, please feel free to correct my answer. Thanks!
I suspect the problem is in your Json you have a space in the field "test " which is causing a null reference exception.
I'm not entirely sure whether is it copy paste mistake or your getting Json string in this format.
Check this working code on removing the space.

C# - JObject.Parse - Invalid JSON

I'm working with an API that is returning JSON.
I have a method that calls the api, and parses the JSON response for the desired nodes.
Up to this point everything has been working fine, except the latest JSON response appears to be malformed.
Other responses come back like:
{
"Keyword":"\"marhope\"",
"TermKey":null,
"Customers":[
{
"Memberships":[ ],
"CompanyId":0,
"ObjectId":112974,
"ObjectType":"Customer",
}
]
}
I use JObject.Parse to bring back the appropriate nodes by name.
The latest JSON response comes back as:
{
[
{
"AnimalId":9079117,
"SpeciesCode":"XX",
}
]
}
As you can see, there is no "name", and the JSON is slightly invalid.
How can I parse this. For the first example I was using the code below, but now that the JSON has no "name", I don't know how to approach this, thoughts?
JObject results = JObject.Parse(csr.SearchCustomer(1, 1, 870, term));
foreach (var resp in results["Customers"])
{
string obj = (string)resp["CompanyId"];
}
Jon Skeet is correct, the second JSON is invalid: you cannot have an array directly inside an object with no property name. The best course of action is to get the API developers to fix the JSON. However, if you're just looking for a quick and dirty workaround, you could strip off the the first and last brace from the invalid JSON and then parse it as an array using JArray.Parse.
string json = #"{
[
{
""AnimalId"":9079117,
""SpeciesCode"":""XX"",
}
]
}";
json = json.Substring(1, json.Length - 2);
JArray array = JArray.Parse(json);
foreach (JObject item in array.Children<JObject>())
{
Console.WriteLine("AnimalId: " + item["AnimalId"]);
Console.WriteLine("SpeciesCode: " + item["SpeciesCode"]);
}

How to parse a JSON array in C#?

Using the MongoDB C# driver how can I parse a JSON array (string) into BsonDocument[]?
We would like to store our mongo aggregation pipelines in separate JSON documents so need a way to parse them.
Not a bad idea if that suits your purposes. Yes the C# driver already supports BSON serialization from a JSON string source:
string json = '[
{ "$match: { "foo": "bar" } },
{ "$group": {
"_id": null,
"count": { "$sum": 1 }
}}
]';
BsonDocument pipeline =
MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonArray>(json);
So you can pull in your aggregation pipeline strings formatted as JSON and use them or manipulate them as BSON documents.
The accepted answer's result is a BsonArray, if you need a BsonDocument[] you'll do something like
BsonSerializer.Deserialize<BsonArray>(yourJsonString).Select(p => p.AsBsonDocument)
and if you need it as a List<BsonDocument>
BsonSerializer.Deserialize<BsonArray>(yourJsonString).Select(p => p.AsBsonDocument).ToList<BsonDocument>()

converting graph api for xml

I'm having trouble converting a string of json facebook graph api, I used the facebook C# and json.Net.
But at conversion time it returns this error: Name can not begin with the '0 'character, hexadecimal value 0x30.
This is the code:
dynamic result = await _fb.GetTaskAsync ("me / feed");
FBxml JsonConvert.DeserializeXNode string = (result.ToString ()). ToString ();
It looks like there is a problem with portion of the json string as mentioned below (taken from your link http://jsfiddle.net/btripoloni/PaLC2/)
"story_tags": {
"0": [{
"id": "100000866891334",
"name": "Bruno Tripoloni",
"offset": 0,
"length": 15,
"type": "user"}]
},
Json cannot create class that begins with a numeric value such as '0'. Try creating the classes using the link http://json2csharp.com/ you will get an idea.
To solve this problem you can create a dynamic object and go through each properties OR create a JsonConverter and write your code in the ReadJson to convert the "0" to a meaningful name. May be this can help you http://blog.maskalik.com/asp-net/json-net-implement-custom-serialization
If this is not your problem then update the question with more information like class structure of FBxml, call stack of the exception (from which line of the json code is throwing the exception), Json version etc.
As keyr says, the problem is with those JSON properties that have numeric names. In XML names can contain numeric characters but cannot begin with one: XML (see the Well-formedness and error-handling section).
My idea was to recursively parse the JSON with JSON.Net, replacing properties that had numeric names:
var jsonObject = JObject.Parse(json);
foreach (var obj in jsonObject)
{
Process(obj.Value);
}
XDocument document = JsonConvert.DeserializeXNode(jsonObject.ToString());
....
private static void Process(JToken jToken)
{
if (jToken.Type == JTokenType.Property)
{
JProperty property = jToken as JProperty;
int value;
if (int.TryParse(property.Name, out value))
{
JToken token = new JProperty("_" + property.Name, property.Value);
jToken.Replace(token);
}
}
if (jToken.HasValues)
{
//foreach won't work here as the call to jToken.Replace(token) above
//results in the collection modifed error.
for(int i = 0; i < jToken.Values().Count(); i++)
{
JToken obj = jToken.Values().ElementAt(i);
Process(obj);
}
}
}
This seemed to work well, prefixing numeric names with _. At this line:
XDocument document = JsonConvert.DeserializeXNode(jsonObject.ToString());
it crashed with an error saying that invalid/not well formed XML had been created. I don't have the actual error with me, but you can run the above code to replicate it.
I think from here you may need to revisit converting the JSON to XML in the first place. Is this a specific requirement?

Categories