How can I deserialize JSON to a simple Dictionarystring,string in ASP.NET?
Json.NET does this...
string json = @"{""key1"":""value1"",""key2"":""value2""}";
var values = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
More examples: Serializing Collections with Json.NET
Deserialize JSON string to Dictionarystring,object
See mridula's answer for why you are getting null. But if you want to directly convert the json string to dictionary you can try following code snippet.
Dictionary<string, object> values =
JsonConvert.DeserializeObject<Dictionary<string, object>>(json);
Deserializing JSON to a Dictionarystring, Item with Item being abstract
You can use custom converter to be able to deserialize to different types in same hierarchy. Also I highly recommend using properties instead of fields. So small reproducer can look like this:
public abstract class Item
{
public virtual ItemType Type => ItemType.NONE; // expression-bodied property
public enum ItemType
{
NONE,
WEAPON,
ARMOUR,
CONSUMABLE,
}
}
public class Weapon : Item
{
public override ItemType Type => ItemType.WEAPON; // expression-bodied property
public string SomeWeaponProperty { get; set; }
}
Custom converter:
public class ItemConverter : JsonConverter<Item>
{
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, Item? value, JsonSerializer serializer) => throw new NotImplementedException();
public override Item ReadJson(JsonReader reader, Type objectType, Item existingValue, bool hasExistingValue, JsonSerializer serializer)
{
// TODO handle nulls
var jObject = JObject.Load(reader);
Item result;
switch (jObject.GetValue("type", StringComparison.InvariantCultureIgnoreCase).ToObject<Item.ItemType>(serializer))
{
case Item.ItemType.WEAPON:
result = jObject.ToObject<Weapon>();
break;
// handle other types
// case Item.ItemType.ARMOUR:
// case Item.ItemType.CONSUMABLE:
case Item.ItemType.NONE:
default:
throw new ArgumentOutOfRangeException();
}
return result;
}
}
and example usage (or mark Item
with JsonConverterAttribute
):
var item = new Weapon();
var settings = new JsonSerializerSettings
{
Converters = { new ItemConverter() }
};
string json = JsonConvert.SerializeObject(item, settings);
var res = JsonConvert.DeserializeObject<Item>(json, settings);
Console.WriteLine(res.GetType()); // prints Weapon
Trying to deserialize JSON into Dictionarystring, Liststring in c#
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);
deserialize json to object with a dictionary System.Text.Json
The System.Text.Json
library doesn't deserialize to fields. If you change your class to use a property instead, your sample JSON will deserialize as expected.
public class Translations
{
public string Key { get; set; }
public Dictionary<string, string> LocalizedValue { get; set; } = new();
}
DeserializeObjectDictionarystring, object JSON string
In your dictionay a key is a string type, but a value is JObject. To get data you have to cast a dictionary value to JObject
Dictionary<string, object> values = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<string, object>>(test);
Dictionary<string,string> products =((JObject) values["products"]).ToObject<Dictionary<string,string>>();
//or
var products = (JObject) values["products"];
var productName= products["name"];
var productQty = products["qty"];
// or directly
productName= (string) ((JObject) values["products"])["name"];
productQty = (string) ((JObject) values["products"])["qty"];
How I can deserialize Json into DictionaryString,ListString
The provided JSON and your ExploreCriteria
class do not describe the same structure.
Your JSON structure is an array that contains a key with an array value. So you can either remove the square brackets to
{"_2":["HR Data","Reformed (Master File)"]}
then your ExploreCriteria
is fitting. Or you can change the JsonConvert call to
var JsonStr = "[{\"_2\":[\"HR Data\",\"Reformed(Master File)\"]}]";
ExploreCriteria Explore = new ExploreCriteria();
var data = JsonConvert.DeserializeObject<IEnumerable<Dictionary<String, List<string>>>>(JsonStr);
Explore.Explore = data.FirstOrDefault();
How to deserialize a json string or stream to Dictionarystring,string with System.Text.Json
Your json does not contain only strings. As a quick (but not performant one) fix you can try to deserealize to Dictionary<string, object>
and then convert it to Dictionary<string, string>
:
async Task<Dictionary<string, string>> DeserializeJson()
{
var jsonText = "{\"number\": 709, \"message\": \"My message here\",\"bool\": true}";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
NumberHandling = JsonNumberHandling.WriteAsString ,
};
var fullResponse = await JsonSerializer.DeserializeAsync<Dictionary<string, Object>>(stream, options);
return fullResponse?.ToDictionary(pair => pair.Key, pair => pair.ToString());
}
Or parse the document manually:
async Task<Dictionary<string, string>> DeserializeJson()
{
var jsonText = "{\"number\": 709, \"message\": \"My message here\",\"bool\": true}";
var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonText));
using var jsonDocument = JsonDocument.Parse(stream);
var dictionary = jsonDocument.RootElement
.EnumerateObject()
.ToDictionary(property => property.Name, property => property.Value.ToString());
return dictionary;
}
Related Topics
C# Structs: Unassigned Local Variable
There Is No Viewdata Item of Type 'Ienumerable<Selectlistitem>' That Has the Key Country
Generic Methods and Method Overloading
Are Timers and Loops in .Net Accurate
Why Is Webbrowser_Documentcompleted() Firing Twice
Very Simple Definition of Initializecomponent(); Method
Enable-Migrations Exception Calling "Setdata" with "2" Argument(S)
List Array Duplicates with Count
How to Display Progress During a Busy Loop
C# Windows 'Open with >' Context Menu Behaviour
Concurrentdictionary Getoradd Async
Unity Eventmanager with Delegate Instead of Unityevent
String Compare C# - Whole Word Match
Looking for C# Equivalent of Scanf
Invalidprogramexception/Common Language Runtime Detected an Invalid Program