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"}
Related
I'm trying to deserialize JSON into a dictionary with strings as keys and lists of strings as values. The way I did it is this:
[
{
"key1": [
"value1.1",
"value1.2"
]
},
{
"key2": [
"value2.1",
"value2.2"
]
},
]
and to deserialize:
Dictionary<string, List<string>> dictionary;
string text = File.ReadAllText(#"Text.json");
dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(text);
I am receiving the errors:
Newtonsoft.Json.JsonSerializationException: 'Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'System.Collections.Generic.Dictionary2[System.String,System.Collections.Generic.List1[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.'
Does anyone have have any insights for me?
Solution As Per Question:
Try this, Hopefully this will help you. https://dotnetfiddle.net/f3u1TC
string json = #"[{""key1"":[""value1.1"",""value1.2""]},{""key2"":[""value2.1"",""value2.2""]}]";
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>[]>(json);
Edit
Updated Solution:
If you don't need an array. Then you have to update your json. Remove array braces [] and add these ones {}
Json
{
{
"key1": [
"value1.1",
"value1.2"
]
},
{
"key2": [
"value2.1",
"value2.2"
]
},
}
C#
string json = #"{""key1"":[""value1.1"",""value1.2""],""key2"":[""value2.1"",""value2.2""]}";
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(json);
JSON syntax for dictionary is { "key1": "val1", "key2: "val2".....}
So if your JSON is structured as follows, your conversion will work as it is.
string json = #"{""key1"":[""value1.1"",""value1.2""],""key2"":[""value2.1"",""value2.2""]}";
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, List<string>>>(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, ...}
I would like to go with DataContractJsonSerializer instead of any third party libs like Json.NET I need to deserialize Json stream which can be one of my C# classes, and I dont know which one it is what i want to do is Deserialize json data -> determine type of this object -> do something with deserialized object according to type of this object. Is there anything to do with DataContractJsonSerializer.KnownTypes Property? Im really new to json.
what i want to do is Deserialize json data -> determine type of this object -> do something with deserialized object according to type of this object. Is there anything to do with DataContractJsonSerializer.KnownTypes Property?
Yes, it is related to the known types. Firstly, you need to specify the type you want to de-serialize in the constructor function. Then you can specify the types may be present in may be present in the object graph.
DataContractJsonSerializer Constructor (Type, IEnumerable)
But I still recommend you using the JSON.NET which will be easier than DataContractJsonSerializer, and the performance is even better. In ASP.NET Web API, JSON.NET is the default JSON serializer.
or JavaScriptSerializer
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, dynamic>>(strRet);
StringBuilder sbErr = new StringBuilder(string.Format("{0} ({1}): {2}", rep.StatusDescription, dict["code"], Environment.NewLine));
if ((dict["errors"] is Dictionary<string, dynamic>)) {
foreach (KeyValuePair<string, dynamic> item in dict["errors"]) {
sbErr.AppendFormat("{0}=", item.Key);
foreach (string item2 in item.Value)
sbErr.AppendFormat("{0}. ", item2);
}
}
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
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.