Deserialize JSON from Firebase - c#

I have a JSON file from firebase that has a list of nodes with their own unique names, If possible I'd like to deserialize the contents all into a list just like a normal JSON array using Newtonsoft.Json like this:
using (StreamReader r = new StreamReader(filePath))
{
string json = r.ReadToEnd();
Console.WriteLine(json);
List<Card> items = JsonConvert.DeserializeObject<List<Card>>(json);
}
However Because of this JSON format from Firebase, each node has a unique name, is there any way to deserialize them like a normal JSON array without editing the format of the JSON using Newtonsoft.Json?
I can safely ignore the node name as I only need the contents of each objects and put them in a list.
{
"131F78DB" : {
"IDNumber" : "5526F",
"Name" : "NAME1"
},
"19505EAD" : {
"IDNumber" : "5132F",
"Name" : "TEMPORARYHR10103"
},
"19539B6D" : {
"IDNumber" : "10102",
"Name" : "TEMPORARYHR10102"
}
}
I will be working with large JSON files like this so if possible I'd like to avoid doing any manual string manipulation to remove the node names.

You can deserialize it as a Dictionary like this:
var items = JsonConvert.DeserializeObject<Dictionary<string, Card>>(json);
That way you can still iterate over it like a list, it matches the format of the json, and you still have all the information available (even if you don't need the key values).
If you really want to have it as a list you could add Select(x => x.Value).ToList() to create a List<Card>.

Related

Jobject using .Add in a nested element

If I had a Json Object:
{
"data":{
"SomeArray":[
{
"name":"test1"
},
{
"name":"test2"
},
{
"name":"test3"
}
]
}
}
And this object is Parsed using Jobject.Parse(jsonString);
How would I add a field under data that holds the count of the items in the array to be forwarded tro another system. The count has already been calculated. I just need to add it in like this:
{
"data":{
"Count" : 3,
"SomeArray" : [
I have tried
myJObject["data"].Add("Count",count);
But .Add does not work here. The only option I see is AddAfterSelf()
Is there no way to just add a simple key value pair without having to create Jproperty first and add it using AddAfterSelf?
Or is the correct way: x["Data"].AddAfterSelf(new JProperty("Count", count));
The problem here is that myJObject["data"] returns an JToken which is base class for JObject.
If you're sure that "data" will be always an object, you can do following
var data = myJObject.GetValue("data") as JObject;
data.Add("Count",120);
You could do this by casting the JToken that you get from myJObject["data"] as a JObject. For example:
var data = (JObject)myJObject["data"];
data.Add("Count", 3);

How to find particular json element from txt file in c# using xpath/jsonpath?

I have a lot of JSON format data into text file and format is like:
[{"ev":"AM","sym":"TMHC","v":1000,"av":74917,"op":18.92,"vw":19.1305,"o":19.13,"c":19.15,"h":19.15,"l":19.13,"a":19.143,"z":90,"n":1,"s":1549380300000,"e":1549380360000},{"ev":"AM","sym":"SPYG","v":7103,"av":184266,"op":35.27,"vw":35.3148,"o":35.3264,"c":35.34,"h":35.34,"l":35.3258,"a":35.3345,"z":710,"n":1,"s":1549380300000,"e":1549380360000},
{"ev":"AM","sym":"AAPL","v":73,"av":1866,"op":35.27,"vw":35.3148,"o":35.3264,"c":35.34,"h":35.34,"l":35.3258,"a":35.3345,"z":710,"n":1,"s":1549380300000,"e":1549380360000}]
So I need to find json element of particular symbol. Like if I use AAPL then it gives us all AAPL element data from txt file. Like
{"ev":"AM","sym":"AAPL","v":73,"av":1866,"op":35.27,"vw":35.3148,"o":35.3264,"c":35.34,"h":35.34,"l":35.3258,"a":35.3345,"z":710,"n":1,"s":1549380300000,"e":1549380360000}
So please can you help me to how should I make it ?
static void xPathUsing()
{
const string filePath = #"D:\Aggregate_Minute_AAPL.txt";
using (StreamReader r = new StreamReader(filePath))
{
string json = r.ReadToEnd();
}
}
As you need to run multiple operations on the data, the best way would be to read the data into memory once (or again whenever the data changes) and hold them in a way that supports fast querying. In order to find a row by the symbol, you could create a dictionary that holds the data.
The following samples use the widely used JSON.NET library for parsing the JSON.
First, you need to define a class that ressembles the schema of your JSON objects, e.g.:
class Row
{
[JsonProperty("sym")]
public string Symbol { get; set; }
public decimal vw { get; set; }
// ...
}
Please note that you can use the JsonProperty attribute in order to be able to assign different names to the properties of the class than in the JSON.
The following sample shows how to read the data from a file and how to convert it to a dictionary:
var input = File.ReadAllText("C:\\Temp\\abc.json");
var rows = JsonConvert.DeserializeObject<IEnumerable<Row>>(input);
var dict = rows.ToDictionary(x => x.Symbol, x => x, StringComparer.OrdinalIgnoreCase);
After preparing your dictionary once, you can get the corresponding row by using the indexer:
var aaplRow = dict["AAPL"];

Map JsonObject to class json

I m trying to populate class object from excel.I received values in json which i m deserializing but i dont want to get List
because in handler class there is function that is of type policy how i can map PolicyNew to class object without List.
var json = JsonConvert.SerializeObject(query);
var policynew = JsonConvert.DeserializeObject<List<PolicyNew>>(json);
Policy policy = Handler.GeneratePolicy(policynew);
//Handler.cs
Handler.GeneratePolicy(PolicyNew policynew)
{
}
If your jsonstring contains an array, you have to deserialize to some sort of List/Array. If you know, you will only need a single element of that list (or you know, that list only contains one element) you can just take the first element of the resulting list.
var policynew = JsonConvert.DeserializeObject<List<PolicyNew>>(json).FirstOrDefault();
If you have control over the generation of the json string, you could change the serialization and not create an array [{"p1": 3, ...}] but a single object {"p1": 3, ...}

How to parse JSON array (as a string) to Dictionary<string,string> in C#?

I have a string in the following format:
{ "Updated" : [ { "FIRST_NAME" : "Aaa", "LAST_NAME" : "Bbb" } ] }
How can I get a dictionary out of this so I can call dict["FIRST_NAME"]?
I've tried the following, but I think they don't work because my string is a JSON array? If that's the case, how do I change it to a regular JSON string? I don't think it needs to be an array with the simple type of data that is in it... The size of the array will never be more than 1 - i.e., there will be no repeating fields.
Dictionary<string, string> dict = serializer.Deserialize<Dictionary<string, string>>(jsonString); //didn't work
JArray jArray = JArray.Parse(jsonString); //didn't work
What you are having is a complex object, which can be parsed as a Dictionary of an Array of a Dictionary!
So you can parse it like:
var dic = serializer.Deserialize<Dictionary<string, Dictionary<string, string>[]>>(jsonString)["Updated"][0];
var firstName = dic["FIRST_NAME"];
var lastName = dic["LAST_NAME"];
It might be easier to just work with a dynamic variable. See Deserialize JSON into C# dynamic object? for more details.

Can you deserialize a JSON string to a C# array?

I'm trying to deserialize the JSON string
[{ "key" : "1", "value" : "open"}, {"key" : "2", "value" : "closed"}, {"key" : "3", "value" : "pending"}]
into a C# array. I'm getting the error "No parameterless constructor defined for type of 'System.Array'." I'm pulling the JSON from a database, then I wanted to deserialize it so I could access the values and update another field in my database with whatever a user passed in. This is just an example that I'm trying though and I need it to be dynamic, not static, since the JSON string contained in the database can be variable.
I tried using a dictionary earlier, but had no luck with that. So I'm trying a different approach now by deserializing it to an array then I was going to populate the dictionary from the array.
This is the method I'm trying to implement with at the moment...although I've tried several others...
IList<Array> ValueArray = new JavaScriptSerializer().Deserialize<IList<Array>>(this.Parameter.ValueList);
//this.Parameter.ValueList just contains my JSON string
I'm thinking that I can't do this without creating my own class?
When I tried using a dictionary, I tried this
Dictionary<string, string> ValueList =
JsonConvert.DeserializeObject<Dictionary<string, string>>(this.Parameter.ValueList);
but received this error
"Cannot deserialize the current JSON array (e.g. [1,2,3]) into type
'System.Collections.Generic.Dictionary`2[System.String,System.String]'
because the type requires a JSON object (e.g. {"name":"value"}) to
deserialize correctly. To fix this error either change the JSON to a
JSON object (e.g. {"name":"value"}) or change the deserialized type to
an array or a type that implements a collection interface (e.g.
ICollection, IList) like List that can be deserialized from a JSON
array. JsonArrayAttribute can also be added to the type to force it to
deserialize from a JSON array. Path '', line 1, position 1."
So I started to try using an array instead.
var list = new JavaScriptSerializer().Deserialize<List<KeyValue>>(json);
public class KeyValue
{
public string key;
public string value;
}
or just use KeyValue temporarily
var dict = new JavaScriptSerializer().Deserialize<List<KeyValue>>(json)
.ToDictionary(x => x.key, x => x.value);
If you are open to use Json.Net , you can directly convert it to Dictionary
var dict = JsonConvert.DeserializeObject<JArray>(json)
.ToDictionary(x => (string)x["key"], x => (string)x["value"]);
Try
List<Dictionary<string, string>> ValueList = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(this.Parameter.ValueList);
But I'm not sure if it is supported by that library.
I just figured it out. There is specific syntax you need to use for a dictionary. The first thing I checked when first trying to address this problem was my JSON string (I used JSONLint.com), and it is indeed valid, which is what threw me off the scent of the bug...
But I just did a little more testing with it by taking a dictionary and serializing it, to see what the JSON looked like...So what the syntax for my JSON should be for converting to a dictionary is this
{"1":"Pending","2":"Open","3":"Closed"}

Categories

Resources