Following is the serialized JSON array I want to convert to IDictionary
[
{
"8475": 25532
},
{
"243": 521
},
{
"3778": 15891
},
{
"3733": 15713
}
]
When I tried to use
JsonConvert.DeserializeObject<IDictionary<string, object>>((string)jarray);
I got an error saying:
Cannot cast 'jarray' (which has an actual type of 'Newtonsoft.Json.Linq.JArray') to 'string'
The JSON deserializer requires only a string.
If you already have the JArray, all you have to do is convert it to a dictionary I guess.
Roughly something like this:
IDictionary<string,object> dict = jarray.ToDictionary(k=>((JObject)k).Properties().First().Name, v=> v.Values().First().Value<object>());
Check this for complete code with an example
I think there might be a better way to convert it to a dictionary though. I'll keep looking.
the JsonConvert.DeserializeObject<T> Method takes a JSON string, in other words a serialized object.
You have a deserialized object, so you'll have to serialize it first, which is actually pointless, considering you have all the information you need right there in the JArray object. If you are aiming just to get the objects from the array as key value pairs, you can do something like this:
Dictionary<string, object> myDictionary = new Dictionary<string, object>();
foreach (JObject content in jarray.Children<JObject>())
{
foreach (JProperty prop in content.Properties())
{
myDictionary.Add(prop.Name, prop.Value);
}
}
To turn your JArray into a string, you'll need to assign the key & values of the dictionary for each element. Mario gave a very accurate approach. But there's a somewhat prettier approach as long as you know how to convert each item into your desired type. The below example is for Dictionary<string, string> but can be applied to any Value type.
//Dictionary<string, string>
var dict = jArray.First() //First() is only necessary if embedded in a json object
.Cast<JProperty>()
.ToDictionary(item => item.Name,
item => item.Value.ToString()); //can be modified for your desired type
Related
I have a JArray with objects have two property. For example:
[
{"Prop1":"key1", "Prop2":"value1"},
{"Prop1":"key2", "Prop2":"value2"},
{"Prop1":"key3", "Prop2":"value3"}
]
And I need to KeyValuePair (or Dictionary doesn't matter) structure in C# such as
key1-value1
key2-value2
key3-value3
Names of Prop1 and Prop2 also can change which means that JArray can have different prop names but number of properties in the object always will be 2. So that I need general method which deserialize the JArray to List<KeyValuePair> .
Given a variable array of type JArray, you can do the following using extension methods from the System.Linq namespace:
var pairs = array
// Cast array items from JToken to JObject.
// You could filter instead using `OfType<JObject>() if nulls might be present
.Cast<JObject>()
// Convert the first and second property values to a KeyValuePair
.Select(o => new KeyValuePair<string, string>((string)o.PropertyValues().ElementAtOrDefault(0),
(string)o.PropertyValues().ElementAtOrDefault(1)))
.ToList();
var dict = pairs.ToDictionary(p => p.Key, p => p.Value);
Sample fiddle
I need to parse lots of long json strings. Newtonsoft.Json is slow and I try to use fastjson.
I don't have the object class so I use the following code to get values when using Newtonsoft.Json:
JObject jo = (JObject)JsonConvert.DeserializeObject(addressBook);
string floor = jo["Street"]["building"]["floor"].ToString();
When I turn to use fastjson and use the JSON.Parse(string), I got an Dictionary<string, object>. And if I want to get the 'floor' value, I need to do the casting for each level like below:
var ob = (Dictionary<string, object>)JSON.Parse(addressBook);
var street = (Dictionary<string, object>)ob["Street"];
var building = (Dictionary<string, object>)street["building"];
var floor= (Dictionary<string, object>)building["floor"];
Does anyone know fastjson support it or not? And can it still be fast?
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.
I'm trying to deserialise some data that looks like:
{
"item1":"value1",
"item2":2,
"item3":true,
"item4":{
"subItem1":"subValue1",
"subItem2":"subValue2",
}
}
In C# I'd like the deserialised object to be an instance of something like:
Dictionary<string, object>
Where the actual type of each Value object is either: string, double, boolean or Dictionary<string,string>
I can trivially use a statement like:
JSONConvert.Deserialise<Dictionary<string,object>>(text);
but that gives me Value objects of types: string, double, boolean or JObject
I'm interested in working out how to route the unknown JObject's into Dictionary<string, string> objects.
Instead of deserializing to a dictionary you can make use of dynamic
dynamic json = JsonConvert.DeserializeObject(text);
Console.WriteLine(json.item1);
Console.WriteLine(json.item4.subItem1);
JObject also implements IDictionary so you can also use it as
var jobj = (JObject)JsonConvert.DeserializeObject(text);
Console.WriteLine(jobj["item4"]["subItem1"]);
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"}