How to parse a JSON array in C#? - 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>()

Related

Youtube Data v3 Api, Get Request sort

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.

C# How to extract certain info long string

Okay I have been trying all day long with Regex and some other methods with no luck, here's what i'm trying to do i will try to make it as simple as I can, this an API and I am getting JSON response from my site like this:
{"user_id":1,"username":"xxx","email":"xxx#xxx.com","gender":"male","title":"","language_id":1,"timezone":"Africa\/Nairobi","visible":1,"activity_visible":1,"user_group_id":3,"secondary_group_ids":"2,4,6,8,11,12,13,16,19,20","message_count":235,"conversations_unread":0,"register_date":1424485355,"last_activity":1436186781,"trophy_points":43,"alerts_unread":2,"avatar_date":1435657653,"avatar_width":180,"avatar_height":224,"gravatar":"","user_state":"valid","is_moderator":0,"is_admin":1,"is_banned":0,"like_count":127,"warning_points":0,"is_staff":1,"advapps":"a:1:{i:0;a:2:{s:5:\"posid\";i:1;s:5:\"count\";i:5;}}","brms_statistic_perferences":"a:1:{i:1;s:1:\"0\";}","bratr_ratings":38,"tc_cui_icon":"","tc_cui_color":"#000000","breta_user_level":5,"breta_curent_level":34,"breta_next_level":45,"credits":"13402154377.480000","brc_points":"999999.000000","br_profile_image":"","br_cropy":"0.00",""}}
What i want to extract is user_group_id and secondary_group_ids then parse the numbers and add them to array then compare them with the given number, i want to check if the member is in that group number (secondary or primary does not matter).
How can i do that with the best and easiest way?
First, deserialize your JSON string to a .NET Dictionary. For example, with JSON.NET:
string json = #"[
{
'Name': 'Product 1',
'ExpiryDate': '2000-12-29T00:00Z',
'Price': 99.95,
'Sizes': null
},
{
'Name': 'Product 2',
'ExpiryDate': '2009-07-31T00:00Z',
'Price': 12.50,
'Sizes': null
}
]";
List<Product> products = JsonConvert.DeserializeObject<List<Product>>(json);
Console.WriteLine(products.Count);
// 2
Product p1 = products[0];
Console.WriteLine(p1.Name);
// Product 1
Then you can use basic LINQ queries against the Dictionary.
I suggest you use DataContractJsonSerializer to deserialize the Json string into a C# object.

Can I use .NET Newtonsoft JSON package (with or without Linq) to deserialize this oddly formatted JSON response?

I receive this JSON response (but I'm not even sure if this is valid JSON. is it?):
"{\"fields\":\"Name,ParentName,Description,StartDate,EndDate,StartMinute,EndMinute\",\"pos\":0,\"start\":0,\"totalRecords\":1001881,\"data\":[[null,\"AAEC 3400 76142\",null,\"2014-05-15T00:00:00\",\"2014-05-15T00:00:00\",840,1050],[null,\"AAEC 3400 76142\",null,\"2014-05-28T00:00:00\",\"2014-05-28T00:00:00\",840,1050],[null,\"ACCT 5400 25030\",null,\"2014-01-08T00:00:00\",\"2014-01-08T00:00:00\",1215,1290],[null,\"ACCT 5400 25030\",null,\"2014-02-19T00:00:00\",\"2014-02-19T00:00:00\",1215,1290]]}"
Is it possible to deserialize this response and access particular values using Newtonsoft JSON package, with or without the LINQ namespace? Can I access specific values from the "data" key?
Currently, my approach is to manipulate this JSON response into regular JSON, so instead of just having a "fields" key and a "data" key followed by lists of values, I end up deserializing normal JSON key/value pairs (like "Name":"null", "ParentName":"AAEC 3400 76142\", . . . ). Then I can access each object in the list's values by key.
But is it possible to access specific values keeping the response the way it came, without parsing/manipulating it, using Newtonsoft JSON package with/without methods in LINQ namespace?
This is how I'm deserializing the json string that I parse/manipulated manually into normal JSON:
var myList = JsonConvert.DeserializeObject<List<MyClass>>(json);
Then I can access values by key off of specific objects in the response by index:
String name = myList[0].Name;
But can I access the value of myList[0].Name without reformatting the JSON response into typical key:value pairs? Does Newtonsoft provide a way to access the value I want from the response the way it came?
Looks like that JSON has been double-serialized. I.e. some class was serialized as a JSON string, then that string was serialized as JSON again, causing JSON control characters including {,} and " characters to be escaped.
This is almost certainly a bug on the server side, you should try to get it fixed there. But if you cannot (for political reasons, say), you can check for this and work around it on the client side:
var token = JToken.Parse(json);
if (token.Type == JTokenType.String)
token = JToken.Parse((string)token);
var myList = token.ToObject<List<MyClass>>();
Update: your root JSON container is an object, not an array, so ToObject<List<MyClass>> won't work. The unwrapped JSON looks like:
{
"fields": "Name,ParentName,Description,StartDate,EndDate,StartMinute,EndMinute",
"pos": 0,
"start": 0,
"totalRecords": 1001881,
"data": [
[
null,
"AAEC 3400 76142",
null,
"2014-05-15T00:00:00",
"2014-05-15T00:00:00",
840,
1050
],
// More of the same
]
}
If you wanted to reformat that into a more traditional array of JSON objects, you could restructure your root JToken like so:
var token = JToken.Parse(json);
if (token.Type == JTokenType.String)
token = JToken.Parse((string)token);
var fields = (string)token.SelectToken("fields");
var fieldList = fields.Split(',');
var root = new JArray();
root.Add(token.SelectTokens("data[*]").OfType<JArray>().Select(a => new JObject(a.Zip(fieldList, (t, s) => new JProperty(s, t)))));
Debug.WriteLine(root);
With the result:
[
{
"Name": null,
"ParentName": "AAEC 3400 76142",
"Description": null,
"StartDate": "2014-05-15T00:00:00",
"EndDate": "2014-05-15T00:00:00",
"StartMinute": 840,
"EndMinute": 1050
},
// More of the same
]
Yes. It is straightforward and simple to deserialize a JSON response formatted in this way using the Newtonsoft JSON package with LINQ namespace. You don't have to manipulate the response string by hand. Set the JSON response string to a string object named "response", use JObject.Parse() to create a dynamic object "jobject", then you can access the "data" JSON key and set it to a JArray object. Then you can loop through each JToken in "jArray". Finally, get the values by their index in the JArray:
dynamic jobject = JObject.Parse(response);
JArray jArray = jobject.data;
foreach (JToken appointment in jArray)
{
parentName = appointment[1];
startMinute = appointment[5];
. . .
}

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"]);
}

Deserialize a Dynamic JSON Array on C# WebForm

Hi I am generating a JSON on my API that I am trying to use on codebehind C# in my web application but I cannot deserialize well.
My JSON has an object with JSON arrays and the element inside the array are dynamic so I cannot create a fixed class with those items becuase my JSON can have N ITEMS.
{
"MAINOBJET": [{
"ITEM1": "23800",
"ITEM2": "Dahl; Police",
"ITEM3": "test#test.net"
},
{
"ITEM1": "23802",
"ITEM2": "Steve ; Police",
"ITEM3": "test2#test.net"
}]
}
So how can I deserialize it to a DataTable, list or a Dictionary?
Thank you
here you can do some thing like the following this example should be able to get you started .. replace the structure / example with your Jason Text
lets say that my JSON Script looks like the following
{
"some_number": 253.541,
"date_time": "2012-26-12T11:53:09Z",
"serial_number": "SN8675309"
"more_data": {
"field1": 1.0
"field2": "hello JSON Deserializer"
}
}
assign you JSON jsonText to a variable and pass it to the following C# Code
using System.Web.Script.Serialization;
var jsonSerialization = new JavaScriptSerializer();
var dictObj = jsonSerialization.Deserialize<Dictionary<string,dynamic>>(jsonText);
Console.WriteLine(dictObj["some_number"]); //outputs 253.541
Console.WriteLine(dictObj["more_data"]["field2"]); //outputs hello JSON Deserializer

Categories