How to make json file using an array of strings? - c#

I have a array of string. I want to make a JSON file from it, mapping it to a hierarchy of nested objects using the strings as property names and final value. For example, if array contains {"A", "B", "C", "D"}, then the resultant JSON file should look like
{
"A": {
"B": {
"C": "D"
}
}
}
Is there any way to do that?

You can generate a nested set of JSON objects from an array of strings using LINQ and a JSON serializer (either json.net or javascriptserializer) as follows:
var input = new[]{"A","B","C","D"};
var data = input
.Reverse()
.Aggregate((object)null, (a, s) => a == null ? (object)s : new Dictionary<string, object>{ { s, a } });
var json = JsonConvert.SerializeObject(data, Formatting.Indented);
The algorithm works by walking the incoming sequence of strings in reverse, returning the string itself for the last item, and returning a dictionary with an entry keyed by the current item and valued by the previously returned object for subsequent items. The returned dictionary or string subsequently can be serialized to produce the desired result.
Demo fiddle here.

Related

Deserialize JSON from Firebase

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>.

Json newtonsoft : Deserialize string array from an Object

My JSON is a very long one and i am fetching only one section "parent_crumbs" from the long JSON
...................,
"parent_crumbs":["Platforms","New platform"],
"promise_by":"2016-08-01",
....
The code I used to fetch value of "parent_crumbs" is
JObject lp_p = JObject.Parse(response_json);
string val= lp_p["parent_crumbs"].ToString();
This returns the following value
"[\r\n \"Platforms\",\"New platform\"\r\n]"
Now I have to do a comparison with the first value from the array as the string is available in a Dictionary as key value and if available return ID
Packages = new Dictionary<string, int>();
Packages.Add("Platforms", 10212);
Packages.Add("New platform", 10202);
Packages.Add("Unknown platform", 10203);
int category=
if(Packages.ContainsKey(val))
{
Packages.TryGetValue(val, out category);
}
So with current code I can't do the comparison straight away due to presence of [\r\n etc.
How to get the value as a string Array without special chars like [\r\n .
Making Model Classes for the JSON for deserialization is not preferred way for me. Since creating class is a big job for me as lot of properties are there in JSON and is dynamic of nature
We can use the below code
var input = "[\r\n \"Platforms\",\"New platform\"\r\n]";
var array =(JArray) JsonConvert.DeserializeObject(input);
bool isEqual = array[0].Value<string>() == "Platforms";
you could also convert it to array with Linq
using System.Linq;
var tmp = lp_p["parent_crumbs"].Select(x => x.ToString());
foreach (var x in tmp)
{
Console.WriteLine(x.ToString());
}
By using Select, it will help you convert it to array rather than to string
You can use DeserializeAnonymousType method for that:
var myType = new
{
parent_crumbs = new []{ "" },
promise_by = default(DateTime)
};
var result = JsonConvert.DeserializeAnonymousType(json, myType);
int category = 0;
string key = result.parent_crumbs[0];
if(Packages.ContainsKey(key))
{
Packages.TryGetValue(key, out category);
}
References: DotNetFiddle Example, DeserializeAnonymousType

How to convert the following data from a DataTable to a JSON object

Currently I am getting data from a database in the following format which I am storing in a DataTable.
Data in Present Format:
Block HouseNo ResidentId
A 101 1
A 102 2
A 103 3
B 101 4
B 102 5
B 104 6
I want to convert it into a JSON object in the following format.
Required Format:
{
"Block A" : [{1:"101"},{2:"102"},{3:"103"}],
"Block B" : [{4:"101"},{5:"102"},{6:"104"}]
}
I have edited the above formats. Can you help me in getting the desired results?
One way to achieve the result you want is by using Json.Net's LINQ-to-JSON API. Here is how you would do that:
// Create a new JObject by grouping the data table rows by block and then
// selecting the groups into JProperties where the block is the property name
// and the property value is a JArray containing JObjects with the resident IDs
// and corresponding house numbers in the group making up the properties of those.
var obj = new JObject(
table.Rows.Cast<DataRow>()
.GroupBy(r => r["Block"])
.Select(g => new JProperty("Block " + g.Key,
new JArray(g.Select(r =>
new JObject(
new JProperty(r["ResidentId"].ToString(), r["HouseNo"])
)
))
))
);
// Convert the JObject to a JSON string
var json = obj.ToString();
Working demo: https://dotnetfiddle.net/smb9oW
You can do this by transforming your DataTable to a Dictionary<string, string []> and then serializing it with a JSON serializer that supports formatting of dictionaries as JSON objects with dictionary keys mapped to JSON property names. json.net and javascriptserializer support this out of the box; as does datacontractjsonserializer in .Net 4.5 and later if you set UseSimpleDictionaryFormat = true.
Transforming from a data table to a dictionary can be done using Linq as follows, after which the dictionary can be serialized directly:
// Choose the property name and value keys.
var propertyKey = "Block";
var valuesKey = "HouseNo";
// Generate the Dictionary<string, string []>
var dictionary = dataTable.AsEnumerable()
// Generate a grouping of all houses for each block
.GroupBy(r => r.Field<string>(propertyKey), r => r.Field<string>(valuesKey))
// And convert to a dictionary of names and array values for JSON serialization.
.ToDictionary(g => propertyKey + " " + g.Key, g => g.ToArray());
// Now serialize to JSON with your preferred serializer. Mine is Json.NET
var json = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
Which produces the following JSON:
{
"Block A": [
"101",
"102",
"103"
],
"Block B": [
"101",
"102",
"104"
]
}
Notes:
Be sure to use the namespace using System.Data; and add a reference to System.Data.DataSetExtensions.dll as I am using some extension methods from there.
I am not aware of any JSON serializer that formats the IEnumerable<IGrouping<TKey, TElement>> returned by GroupBy() as a JSON object with group keys mapped to property names, which is why it is necessary to generate a final dictionary representation from the intermediate grouped representation.
Sample working .Net fiddle.

Deserialise JSON with unnecessary array as first item

[{
"$type": "foo",
"key" : "value"
}]
I don't serialise this message, its done as part of a framework.
The array is unnecessary, I'm just interested in first type and values etc, this is invariable.
I CAN do it using the following code, but it just feels a bit nasty! I know I am being particularly stupid, I started going down the road of creating a SerializationBinder but then thought I would like to get on with my life. It can't be that hard!
var json = reader.ReadToEnd().TrimStart('[').TrimEnd(']');
var foo = JsonConvert.DeserializeObject<Foo>(json , new JsonSerializerSettings()
{
TypeNameHandling = TypeNameHandling.All
});
As based on the comments the JSON string in the example is a valid JSON Array. Therefore the best solution would be to parse the JSON as an Array and then capture the first element. A basic example would be.
var foo = JsonConvert.DeserializeObject<Foo[]>(json)[0]
For a safer way to handle this would be to first get the array and then check if the result is valid such as.
Foo foo = fooArray.Length > 0 ? fooArray[0] : null;
And for a more generic solution can be done as a generic method.
static T DeserializeObjectFromArray<T>(string json)
where T: class
{
var arr = JsonConvert.DeserializeObject<T[]>(json);
return arr != null && arr.Length > 0 ? arr[0] : null;
}
Where in this method you can simply call
Foo foo = DeserializeObjectFromArray<Foo>(json);
This does the same as the second solution but can be reused for generic classes.
Cheers.
You can deserialize this to a list of dictionary like below
List<Dictionary<string, string>> values = JsonConvert.DeserializeObject<List<Dictionary<string, string>>>(a);

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.

Categories

Resources