Serializing a class containing a Dictionary of Dictionay - c#

I have defined a class which contains only one member of type dictionary of dictionary. I want to serialize it to JSON format and hence using JavaScriptSerializer.
[Serializable]
class X
{
private readonly Dictionary<string, Dictionary<string, string>> dic;
public X()
{
dic = new Dictionary<string, Dictionary<string, string>>();
}
public void Add()
{
this.dic.Add("x", new Dictionary<string, string>() { { "a", "b" } });
}
}
class Program
{
static void Main(string[] args)
{
var x = new X();
x.Add();
string msg = new JavaScriptSerializer(new SimpleTypeResolver()).Serialize(x);
var y = new JavaScriptSerializer(new SimpleTypeResolver()).Deserialize<X>(msg);
}
}
Now, the above code run successful without any error/exception but the results are not as excepted. The serialized string of class X in the above code is
{"__type":"Testing.X, Testing, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"}
Can anybody tell me whats the problem in the above code and what I'm missing? Also, if in the above class, I change the inner dictionary type to Dictionary<string, IEntity> then what all I have to do to serialize it.

JavaScriptSerializer is designed to only pull public properties by default. Once you expose the field through a getter or setter you should be able to serialize this data.
[Serializable]
class X
{
private readonly Dictionary<string, Dictionary<string, string>> dic;
public X()
{
dic = new Dictionary<string, Dictionary<string, string>>();
}
public void Add()
{
this.dic.Add("x", new Dictionary<string, string>() { { "a", "b" } });
}
//Property exposing private field 'dic'.
public Dictionary<string, Dictionary<string, string>> Dictionary
{
get
{
return dic;
}
}
}
class Program
{
static void Main(string[] args)
{
var x = new X();
x.Add();
string msg = new JavaScriptSerializer(new SimpleTypeResolver()).Serialize(x);
var y = new JavaScriptSerializer(new SimpleTypeResolver()).Deserialize<X>(msg);
}
}
In this case, the string contains the following output (look to the very end):
{"__type":"ConsoleApplication1.X, ConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null","Dictionary":{"x":{"a":"b"}}}

Related

The call is ambiguous between IDictionary<string, object> and IDictionary

I am using a Library with a class that have the following constructors:
public JobDataMap(IDictionary<string, object> map);
public JobDataMap(IDictionary map);
I created an instance of JobDataMap:
var jdm = new JobDataMap(new Dictionary<String, Object> {
{ "Manager", myObject }
});
But I am getting the compilation error:
The call is ambiguous between the following methods or properties:
'JobDataMap.JobDataMap(IDictionary<string, object>)' and 'JobDataMap.JobDataMap(IDictionary)'
How to solve this?
You can enforce the type being passed like so:
var jdm = new JobDataMap((IDictionary<string, object>)new Dictionary<String, Object> {
{ "Manager", myObject }
});
Or you could make a factory method and make the non-generic constructor (I'm assuming you use this less) private:
public class JobDataMap
{
public JobDataMap(IDictionary<string, object> map)
{
}
private JobDataMap(IDictionary map)
{
}
public static JobDataMap FromNonGenericMap(IDictionary map)
{
return new JobDataMap(map);
}
}
Usage:
var jdm = JobDataMap.FromNonGenericMap(someNonGenericDictionary);
and then you can use the regular generic one like so:
var jdm = new JobDataMap(new Dictionary<String, Object> {
{ "Manager", myObject }
});
You can cast it to the type for the constructor you want it to use:
var jdm = new JobDataMap((IDictionary<string, object>) new Dictionary<String, Object> {
{ "Manager", new object() }
});
This design does seem a bit dubious, however...

How to have a singleton class and use it through out the application c#

I have a class which deserializes a JSON file.
The JSON is styleconfig.json
{
"Style1": {
"Font": "Arial",
"width": "25px",
"className": "Grid-side"
} ,
"Style2": {
"Font": "Arial",
"width": "25px",
"className": "Grid-side"
}
}
I have a classA:
var jss = new JavaScriptSerializer();
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
Dictionary<string, string> sData = jss.Deserialize<Dictionary<string, string>>(json);
So I need to call this classA every time in my application
For Example
There are two pages...Page1 and page2 both the style variables are there on json
so every time I need to call the classA to Deserialize
page1 call classA to Deserialize
page2 call classA to Deserialize
So this may affect the performance.End of the day the JSON file is the same for the whole application
So my requirement is to run classA only once when I login into the application and make the
Deserialized JSON object throughout the application.
I need some help with this
You could do this with a static class and use a Lazy<> to ensure it is loaded only once:
public static class A
{
private static Lazy<Dictionary<string, string>> _data = new Lazy<Dictionary<string, string>>(() => GetData());
public static Dictionary<string, string> Data => _data.Value;
private static Dictionary<string, string> GetData()
{
var jss = new JavaScriptSerializer();
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
return jss.Deserialize<Dictionary<string, string>>(json);
}
}
You should use Lazy<T> for that. Here's an example:
static class ClassA
{
private static Lazy<Dictionary<string, string>> _json = new Lazy<Dictionary<string, string>>(ReadJson);
private static Dictionary<string, string> ReadJson()
{
var jss = new JavaScriptSerializer();
var json = new StreamReader(context.Request.InputStream).ReadToEnd();
return jss.Deserialize<Dictionary<string, string>>(json);
}
public Dictionary<string, string> Json => _json.Value;
}
Now the first time you read ClassA.Json the file will be parsed and read. The subsequent calls will just return the cached value.
If I have correctly understood your question, apart from a lazy field already explained in other comments, have you tried a simple property?
public class ClassA
{
//Just a singleton model
static ClassA _SingleInstance = null;
public static ClassA SingleInstance
{
get
{
if (_SingleInstance == null)
_SingleInstance = new ClassA();
return _SingleInstance;
}
}
Dictionary<string, string> _Data = null;
public Dictionary<string, string> Data
{
get
{
if (_Data == null)
LoadData();
return _Data;
}
}
private ClassA()
{
//your constructor
}
//As pointed out by torvin, to avoid multithread races, load must
//be synchronized
private void LoadData()
{
lock(LoadMutex)
{
if (_Data == null)
{
var jss = new JavaScriptSerializer();
string json = new StreamReader(context.Request.InputStream).ReadToEnd();
_Data = jss.Deserialize<Dictionary<string, string>>(json);
}
}
}
private static readonly object LoadMutex = new object();
}
and then from Page1 and Page2, you call it:
Dictionary<string, string> myConfigData = ClassA.SingleInstance.Data;

C# Assign static dictionary to filtered version of other dictionary in static class

I have a class, with some global and constant dictionaries. Like:
public static class Constants
{
public static Dictionary<string, MyObject> MyDictionary= new Dictionary<string, MyObject>()
{
{"first", new MyObject()},
{"second", new MyObject()},
};
}
Lets say I would like another dictionary, to be like that only with some added and removed elements. Is there a way to achieve that, within the static class? I imagine something like:
public static Dictionary<string, MyObject> MyOtherDictionary = MyDictionary.Remove("second").Add("Third", new MyObject())
But I know that does not work, so is there any way I can achieve this?
No, that doesnt work in this way for two reasons:
Remove returns a bool, you can't use Add on a bool
even if you make it compile, you don't want to modify the other dictionary but you want to create a new dictionary which contains similar items, you can use the constructor:
public static Dictionary<string, MyObject> MyOtherDictionary;
// ...
static Constants
{
MyOtherDictionary = new Dictionary<string, MyObject>(MyDictionary);
MyOtherDictionary.Remove("second");
MyOtherDictionary.Add("Third", new MyObject());
}
You could do it using properties instead
public static class Constants
{
public static Dictionary<string, MyObject> myDictionary
{
get
{
return new Dictionary<string, MyObject>()
{
{ "first", new MyObject()},
{ "second", new MyObject()},
};
}
}
static Dictionary<string, MyObject> _myOtherDictionary;
public static Dictionary<string, MyObject> myOtherDictionary
{
get
{
_myOtherDictionary = myDictionary;
_myOtherDictionary.Remove("first");
_myOtherDictionary.Add("third", new MyObject());
return _myOtherDictionary;
}
}
}

get access of dictionary elements in to another class

I have a class with two dictionaries .and i want access these dictionary in other class.these is my class.
{
public class DictionaryLines
{
private Dictionary<string, string> line1dictionary;
private Dictionary<string, string> line2dictionary;
public DictionaryLines()
{
line1dictionary = new Dictionary<string, string>();
line2dictionary = new Dictionary<string, string>();
line1dictionary.Add("A1", "Miyapur");
line1dictionary.Add("A2", "JNTU College");
line1dictionary.Add("A3", "KPHB Colony");
line1dictionary.Add("A4", "Kukatpally");
line1dictionary.Add("A5", "Balanagar");
line1dictionary.Add("A6", "Moosapeta");
line1dictionary.Add("A7", "Bharath nagar");
line1dictionary.Add("A8", "Erragadda");
line2dictionary.Add("B1", "JBS");
line2dictionary.Add("X3", "Parade Grounds");
line2dictionary.Add("B3", "Secundrabad");
line2dictionary.Add("B4", "Gandhi Hospital");
}
}
how i can call this dictionary into other class..thank you
Adding two public properties which return the fields would be the easiest way.
{
public class DictionaryLines
{
private Dictionary<string, string> line1dictionary;
private Dictionary<string, string> line2dictionary;
public Dictionary<string, string> Line1Dictionary { get { return line1dictionary; } }
public Dictionary<string, string> Line2Dictionary { get { return line2dictionary; } }
public DictionaryLines()
{
line1dictionary = new Dictionary<string, string>();
line2dictionary = new Dictionary<string, string>();
line1dictionary.Add("A1", "Miyapur");
line1dictionary.Add("A2", "JNTU College");
line1dictionary.Add("A3", "KPHB Colony");
line1dictionary.Add("A4", "Kukatpally");
line1dictionary.Add("A5", "Balanagar");
line1dictionary.Add("A6", "Moosapeta");
line1dictionary.Add("A7", "Bharath nagar");
line1dictionary.Add("A8", "Erragadda");
line2dictionary.Add("B1", "JBS");
line2dictionary.Add("X3", "Parade Grounds");
line2dictionary.Add("B3", "Secundrabad");
line2dictionary.Add("B4", "Gandhi Hospital");
}
}
//Change the scope private to public like
public Dictionary<string, string> line1dictionary;
public Dictionary<string, string> line2dictionary;
You can access private members in another class using reflection.
like this:
public class DictionaryLines
{
private Dictionary<string, string> line1dictionary;
private Dictionary<string, string> line2dictionary;
public DictionaryLines()
{
line1dictionary = new Dictionary<string, string>();
line2dictionary = new Dictionary<string, string>();
line1dictionary.Add("A1", "Miyapur");
line1dictionary.Add("A2", "JNTU College");
line1dictionary.Add("A3", "KPHB Colony");
line1dictionary.Add("A4", "Kukatpally");
line1dictionary.Add("A5", "Balanagar");
line1dictionary.Add("A6", "Moosapeta");
line1dictionary.Add("A7", "Bharath nagar");
line1dictionary.Add("A8", "Erragadda");
line2dictionary.Add("B1", "JBS");
line2dictionary.Add("X3", "Parade Grounds");
line2dictionary.Add("B3", "Secundrabad");
line2dictionary.Add("B4", "Gandhi Hospital");
}
}
class Program
{
static void Main(string[] args)
{
var cls = new DictionaryLines().GetType();
var attrs = cls.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach(var k in attrs)
{
Console.WriteLine("----------------------"+k.Name+"------------------------------");
foreach (var j in (Dictionary<string, string>)k.GetValue(new DictionaryLines()))
{
Console.WriteLine("Key = "+j.Key +" & Value = "+j.Value);
}
}
Console.Read();
}
}

How to access Dictionary from other Class's function in C#?

I have create a Class named "EngDictionary". and Then i define a dictionary in a function
e.g:
public void Dict()
{
Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("Classifieds", "Kleinanzeigen");
//d.Add("windows", 5);
}
Now i want to access above defined dictionary from my main class for retrieving the keys and values of my Dictionary. Please Suggest me some code. I am using Visual C# 2008 Express Edition, Win Application
Declare Dictionary as class property.
public class Dict {
private Dictionary<string, string> dict;
public SomeDictionary { get dict; set dict = value; }
public Dict() {
dict = new Dictionary<string, string>();
dict.Add("Classifieds", "Kleinanzeigen");
}
}
In other class:
Dict d = new Dict();
string test = d.SomeDictionary["Classifieds"];
Console.WriteLine(test);
return the dictionary from the method.
public Dictionary<string, string> Dict() {.... ; return d;}
In your main class.
EngDictionary dict = new EngDictionary();
Dictionary<string, string> dictionary = dict.Dict();
You can declare Dictionary<string, string> d as a member variable of your class , and initialize this object in the class constructor.You can have a getter method to get the dictionary in other classes.
public class EngDictionary
{
Dictionary<string, string> dictionary;
public void EngDictionary()
{
dictionary = new Dictionary<string, string>();
dictionary.Add("Classifieds", "Kleinanzeigen");
....
}
public Dictionary<string, string> getDictionary()
{
return this.dictionary;
}
}
I have a class
public class Dict
{
public Dictionary<string, string> SomeDictionary { get; } = new Dictionary<string, string>()
{
{ "Classifieds", "Kleinanzeigen" }
};
}
then in any other class
Dict Dic = new Dict();
foreach (var item in Dic.SomeDictionary)
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}

Categories

Resources