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);
Related
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);
I'm quite new to JSON, and am currently learning about (de)serialization.
I'm retrieving a JSON string from a webpage and trying to deserialize it into an object. Problem is, the root json key is static, but the underlying keys are dynamic and I cannot anticipate them to deserialize. Here is a mini example of the string :
{
"daily": {
"1337990400000": 443447,
"1338076800000": 444693,
"1338163200000": 452282,
"1338249600000": 462189,
"1338336000000": 466626
}
}
For another JSON string in my application, I was using a JavascriptSerializer and anticipating the keys using class structure. What's the best way to go about deserializing this string into an object?
Seriously, no need to go down the dynamic route; use
var deser = new JavaScriptSerializer()
.Deserialize<Dictionary<string, Dictionary<string, int>>>(val);
var justDaily = deser["daily"];
to get a dictionary, and then you can e.g.
foreach (string key in justDaily.Keys)
Console.WriteLine(key + ": " + justDaily[key]);
to get the keys present and the corresponding values.
You can use dynamic in .NET 4 or later. For example with JSON.NET I can do:
dynamic obj = JsonConvert.Deserialize<dynamic>("{x: 'hello'}");
You can then do:
var str = obj.x;
However, unsure how it will handle numeric keys. You can of course just use JObject directly itself, for example:
var obj = JObject.Parse("{'123456': 'help'}");
var str = obj["123456"];
Whenever you have JSON with dynamic keys it can usually be deserialized into a Dictionary<string, SomeObject>. Since the inner JSON keys are dynamic (in this question) the JSON can be modelled as:
Dictionary<string, Dictionary<string, int>>
I would recommend using NewtonSoft.Json (JSON.Net) or System.Text.Json (if you're working in .NET-Core 3.0 and up).
Newtonsoft.Json
Use DeserializeObject<T> from JsonConvert:
var response = JsonConvert.DeserializeObject<Dictionary<string, Dictionary<string, int>>>(json);
System.Text.Json
Use Deserialize<T> from JsonSerializer:
var response = JsonSerializer.Deserialize<Dictionary<string, Dictionary<string, int>>>(json);
This is not convenient to use, because in с# can not be defined a variable starts with a number. Add prefix to keys.
Or try this:
string json = "
{ daily:[
{ key: '1337990400000', val:443447 },
{ key: '1338076800000', val:444693 },
{ key: '1338163200000', val:452282 },
{ key: '1338249600000', val:462189 },
{ key: '1338336000000', val:466626 }]
}";
public class itemClass
{
public string key; // or int
public int val;
}
public class items
{
public itemClass[] daily;
}
items daily = (new JavascriptSerializer()).Deserialize<items>(json);
Then you can:
var itemValue = items.Where(x=>x.key=='1338163200000').Select(x=>x.val).FirstOrDefault();
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 update a JSON file with converted list of strings to JSON square brackets "list".
My strings list:
var animals = new List<string>() { "bird", "dog" };
Using this code:
string json = File.ReadAllText(filePath);
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject(json);
var serializedObject = JsonConvert.SerializeObject(animals);
jsonObj["animals"] = serializedObject;
string output = Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj, Newtonsoft.Json.Formatting.Indented);
File.WriteAllText(filePath, output);
Old JSON file:
{
"animals": ["cat", "fox"]
}
The new JSON file should be:
{
"animals": ["bird", "dog"]
}
But what i get is:
{
"animals": "[\"bird\", \"dog\"]"
}
Any help is appreciated!
Thanks
Your serializedObject is a string, but you don't need it at all it.
As you don't deserialize to a concrete type, your jsonObj["animals"] is just a JArray. So you need this:
dynamic jsonObj = JsonConvert.DeserializeObject(json);
jsonObj["animals"] = JArray.FromObject(animals);
Now you can serialize it back through JsonConvert.SerializeObject.
If that jsonObj was a regular object you could just set the value of the animals property. The same would work if it was an ExpandoObject. JsonConvert.DeserializeObject(json) though generates a Json.Net type whose data must be valid Json.NET types.
You can assing the list contents as a JArray, eg :
var animals = new List<string>() { "bird", "dog" };
dynamic jsonObj = Newtonsoft.Json.JsonConvert.DeserializeObject("{'moo':1}");
jsonObj.animals= new JArray(animals);
var result=JsonConvert.SerializeObject(jsonObj);
The result will be :
{"moo":1,"animals":["bird","dog"]}
Adding a new property will work only if the file contains a JSON dictionary. If you know that the file will alway contain a dictionary, you can cast the deserialization result to JObject, and add the new property through JObject's indexer :
var jsonObj = (JObject)JsonConvert.DeserializeObject("{'moo':1}");
jsonObj["animals"]= new JArray(animals);
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.