Map JsonObject to class json - c#

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

Related

Converting multiple JSON arrays

I have been kindly provided with the code below to convert a JSON array to a single object. I would like to use the same code to change multiple properties. All arrays will have a single object.
I would like to add some code that will walk through the JSON and execute the code below on any properties that have been found. Most properties are nested, hence the need to walk through the JSON.
// Load the JSON from a file into a JObject
JObject o1 = JObject.Parse(File.ReadAllText(#"output.json"));
// Get the desired property whose value is to be replaced
var prop = o1.Property("to_Description");
// Replace the property value with the first child JObject of the existing value
prop.Value = prop.Value.Children<JObject>().FirstOrDefault();
// write the changed JSON back to the original file
File.WriteAllText(#"output.json", o1.ToString());
Replace the middle two lines with these:
// Find all properties anywhere in the JSON whose values are arrays
var arrayProperties = o1.Descendants()
.OfType<JProperty>()
.Where(p => p.Value.Type == JTokenType.Array);
foreach (JProperty prop in arrayProperties)
{
// Replace the property value with the first child JObject of the existing value
prop.Value = prop.Value.Children<JObject>().FirstOrDefault();
}
Fiddle: https://dotnetfiddle.net/iP8Ibd

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

Pass complex json via hidden variable and read in mvc 3 controller

I want to do the following.
Pass a complex json object in a hidden input variable
Get that hidden variable through the form collection object.
Convert that hidden text value to a dynamic object which I can loop through to
get the data from it
So I think the first two items above I can do.
$("#hiddenVariableID").val(JSON.stringify(data));
Have a parameter called FormCollection collection in the MVC controller.
Then get the value the following way String data =
collection.Get("hiddenVariableID");
?? Not sure how to do this.
The data I'm passing is an array of objects. The objects are never the same so that is why I need to convert the results in some type of dynamic object that I can loop through.
I can't do an ajax call to do this because I want to stream down the data passed in the hidden variable. So it has to be through a form submission.
Thank you,
-Tesh
You can at that point use some JSON parser to convert between the string and a JSON object you can access dynamically. There are many JSON parsers out there, the code below shows how it can be done with two of them: the JavaScriptSerializer (part of the .NET Framework), and the JSON.NET (a non-MS library, but which IMO is really good).
public static void Test()
{
string JSON = #"[
{'name':'Scooby Doo', 'age':10},
{'name':'Shaggy', 'age':18},
{'name':'Daphne', 'age':19},
{'name':'Fred', 'age':19},
{'name':'Velma', 'age':20}
]".Replace('\'', '\"');
Console.WriteLine("Using JavaScriptSerializer");
JavaScriptSerializer jss = new JavaScriptSerializer();
object[] o = jss.DeserializeObject(JSON) as object[];
foreach (Dictionary<string, object> person in o)
{
Console.WriteLine("{0} - {1}", person["name"], person["age"]);
}
Console.WriteLine();
Console.WriteLine("Using JSON.NET (Newtonsoft.Json) parser");
JArray ja = JArray.Parse(JSON);
foreach (var person in ja)
{
Console.WriteLine("{0} - {1}", person["name"].ToObject<string>(), person["age"].ToObject<int>());
}
}

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"}

Json Array - retrieve first record in C#

I am obtaining a JSON array in a dynamic object.
How can I obtain the first item( equivalent of First for List collection)?
How can I check if Json array is empty
If that's all you want to do with it, and if the underlying object implements IEnumerable, you could use:
foreach (dynamic item in array)
{
// Use it here
break;
}
Or use First explicitly:
dynamic first = Enumerable.First(array);

Categories

Resources