c# Dictionary to Json and Dictionary to Dictionary, how? - c#

I trying to do Dictionary with access as dictionary["1"] -> "Some":
public static Dictionary<string, string> dictionary { get; private set; } = new();
string json = Newtonsoft.Json.JsonConvert.SerializeObject(dictionary);
json ={
"1": "Some",
"2222": "Data",
"4123": "In",
"107": "That",
"4213213": "Json"
}
after, I want read it:
string fileContents = sr.ReadToEnd();
dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(fileContents);
and getting error:
Newtonsoft.Json.JsonSerializationException: "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"})
I tried:
string json = Newtonsoft.Json.JsonConvert.SerializeObject(dictionary.ToArray());
with json output
[
{
"Key": "1",
"Value": "Some"
},
{
"Key": "2222",
"Value": "Data"
}
]
and after
dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, string>>(fileContents);
getting the same error. Where Is a mistake?

Check what contains string fileContents= sr.ReadToEnd(); IMHO You have a bug there, the file must be contains the previous json or a corrupted text.
After you fix it , then for the second case instead of a dictionary it is more efficient to use a KeyValuePair list
var list = JsonConvert.DeserializeObject<List<KeyValuePair<string,string>>>(json);
or you can still use a dictionary, but only a list of dictionaries
var dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject< List<Dictionary<string, string>>>(json);

Related

Need ideas how to parse the following JSON format

I have an API that returns JSON data in the following structure:
{
"85f78300-d993-4b7e-a8d0-8d39a4ba9d2a": {},
"4000fda7-18af-463f-b694-bbafe5d23a48": {
...
}
...
}
It should represents a list of objects referenced by a GUID. Typically a list of of Objects would look like this:
{
"objects": [
{...},
{...},
...
]
}
Currently I have no clue how to parse this result properly. Does anyone have a clue for me?
You could treat it as a Dictionary<Guid, object>. You can replace object with your data type.
string json = "{\"85f78300-d993-4b7e-a8d0-8d39a4ba9d2a\": {\"prop\": \"value\"}}";
var dict = System.Text.Json.JsonSerializer.Deserialize<Dictionary<Guid, object>>(json);

C# Json Convert any dynamic object to key value pairs not class

i have a Json
{
"test1.png": "123",
"image.png": "456",
"pdffile.pdf": "789"
}
how can i convert to C# dictionary or table
How about this?
string serializedDic = #"{
""test1.png"": ""123"",
""image.png"": ""456"",
""pdffile.pdf"": ""789""
}";
Dictionary<string, string> dict =
JsonSerializer
.Deserialize<Dictionary<string, string>>(serializedDic);
Use Newtonsoft Json library.
First, create your own class, with 3 properties name it as you want. Add JsonPropertyAttribute with name exactly same as 3 json property.
Then, just Deserialize your json file to get your object.
Use Newtonsoft Json library
string json = #"{
"test1.png": "123",
"image.png": "456",
"pdffile.pdf": "789"
}";
var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

Trying to deserialize JSON into Dictionary<string, List<string>> in c#

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);

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