Resolved Facing an issue including Dictionary method in Json class

Palak Shah

Well-known member
Joined
Apr 29, 2020
Messages
97
Programming Experience
1-3
I had JSON string which I converted to JSON Class, and now I want to add Dictionary method insode my JSON class which will return me certain values from JSON class variables

And for that I am facing an issue including Dictionary method in Json class c#

Can someone help where can I include that method?

My JSON Class Model:
namespace JsonModel
{
    using Newtonsoft.Json;
    using System.Collections.Generic;

    public partial class StringResourcesX
    {
        [JsonProperty("StringResources")]
        public StringResources StringResources { get; set; }
    }

    public partial class StringResources
    {
        
        [JsonProperty("Culture")]
        public Culture Culture { get; set; }

        public Culture_ Culture_ { get; set; }
        public FullName FullName { get; set; }

        public Dictionary<Culture_, FullName> CulturalNames { get; set; }
    }
    
    

    public partial class Culture
    {
        [JsonProperty("Cultures")]
        public Cultures Cultures { get; set; }

        [JsonProperty("CulturalName")]
        public CulturalName CulturalName { get; set; }
    }

    public partial class CulturalName
    {
        [JsonProperty("AE")]
        public AE AE { get; set; }

        [JsonProperty("GB")]
        public GB GB { get; set; }

        
    }

    public partial class AE
    {
        [JsonProperty("AE_Name")]
        public string AE_Name { get; set; }

        [JsonProperty("AE_LastName")]
        public string AE_LastName { get; set; }
    }

    
    public partial class GB
    {
        [JsonProperty("GB_Name")]
        public string GB_Name { get; set; }

        [JsonProperty("GB_LastName")]
        public string GB_LastName { get; set; }
    }

    public partial class Cultures
    {
        [JsonProperty("Culture_UK")]
        public string Culture_UK { get; set; }

        [JsonProperty("Culture_US")]
        public string Culture_US { get; set; }

        [JsonProperty("Culture_CA")]
        public string Culture_CA { get; set; }

        [JsonProperty("Culture_DE")]
        public string Culture_DE { get; set; }

        [JsonProperty("Culture_JP")]
        public string Culture_JP { get; set; }
    }

    public enum Culture_
    {
        GB,
        US,
        IT,
        FR,
        CA,
        DE,
        SE,
        NL,
        NZ,
        AU,
        AE,
        CN,
        JP,
        IE,
        IN,
        ES
    }

    public class FullName
    {
        public string First;
        public string Last;
        public FullName(string first, string last)
        {
            this.First = first;
            this.Last = last;
        }
    }
}


Method Which I want to include in class model:
public static Dictionary<Culture_, FullName> CulturalNames = new Dictionary<Culture_, FullName>
        {
            {Culture_.GB, new FullName(Culture.CulturalName.GB.GB_Name, Culture.CulturalName.GB.GB_LastName)},{Culture_.AE, new FullName(Culture.CulturalName.AE.AE_Name, Culture.CulturalName.AE.AE_LastName)}
        };

But I'm getting compile time error as " a field initializer cannot reference the nonstatic field ", so I'm not able to understandhow and where should I include my method which will work
 
If a field is not static. What standard do you follow to access a non-static field?

There are two answers to that, depending on whether you want to reuse the field or overwrite the field value every time you need to reuse it. Which do you need?

Edit typo
 
If a field is not static. What standard do you follow to access a static field?

There are two answers to that, depending on whether you want to reuse the field or overwrite the field value every time you need to reuse it. Which do you need?
So basically what I want is, I want to use combination of First name and last name as Cultural names so from data we get from JSON string, in json class want to use them in dictionalry method, which I can use in different classes
 
Re-read my first reply. Sorry, I meant non static. lol

Basically, you need to ask yourself if the property you are using should be called by instance or static modifiers instead.
 
Re-read my first reply. Sorry, I meant non static. lol

Basically, you need to ask yourself if the property you are using should be called by instance or static modifiers instead.
I need static modifier so I can use them in other classes as below


C#:
if (StringResources.CulturalNames.ContainsKey(cultureCode))
            {
                payerDetails.UserDetails.Name = StringResources.CulturalNames[cultureCode].First;
                payerDetails.UserDetails.LastName = StringResources.CulturalNames[cultureCode].Last;
            }
 
I do not want to use static modifier in my JSON class model, and if I am not using it then gives compile error so I am unable to find a way how I can handle

Basically below errors I am receiving if I am not using static
P.S: I am sharing image since that way it would be really easy t understand the error

1597242153373.png


1597242170080.png
 
I could find the solution as mentioned below

C#:
namespace ContradoWebsiteAutoFramework.JsonModel
{
    using Framework.Config;
    using Framework.Helpers;
    using Newtonsoft.Json;
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;

    using Culture_ = Framework.Constants.Culture;

    public class StringResourcesTestData
    {
        public const string jsonFilePath = "JsonData\\Constants\\StringResources.json";
        public static StringResourcesX StringResources { get; set; }

        private StringResourcesTestData()
        {

        }

        public static StringResourcesX Get()
        {
            if(StringResources == null)
                StringResources = JsonHelper
                    .GetTestParams<StringResourcesJson>(ConfigProvider.BuildPath(jsonFilePath))
                    .StringResources;

            return StringResources;
        }
    }

    public partial class StringResourcesJson
    {
        [JsonProperty("StringResources")]
        public StringResourcesX StringResources { get; set; }
    }

    public partial class StringResourcesX
    {
    
        [JsonProperty("Culture")]
        public Culture Culture { get; set; }

    }

  
    public partial class Culture
    {
        [JsonProperty("Cultures")]
        public Cultures Cultures { get; set; }

        [JsonProperty("CulturalName")]
        public CulturalName CulturalName { get; set; }
      
    }

    public partial class CulturalName
    {   
        public class FullName
        {
            public string First;
            public string Last;
            public FullName(string first, string last)
            {
                this.First = first;
                this.Last = last;
            }
        }
        public Dictionary<Culture_, FullName> CulturalNames;

        public FullName GetName(Culture_ culture_)
        {
            if (CulturalNames == null)
            {
                CulturalNames = new Dictionary<Culture_, FullName>
                {
                    {Culture_.GB, new FullName (GB.GB_Name, GB.GB_LastName)},{Culture_.US, new FullName(US.US_Name ,US.US_LastName)},
                    {Culture_.IT, new FullName(IT.IT_Name, IT.IT_LastName)},{Culture_.ES, new FullName(ES.ES_Name, ES.ES_LastName)},
                    {Culture_.FR, new FullName(FR.FR_Name, FR.FR_LastName)},{Culture_.AE, new FullName(AE.AE_Name, AE.AE_LastName)},
                    {Culture_.DE, new FullName(DE.DE_Name, DE.DE_LastName)},{Culture_.NL, new FullName(NL.NL_Name, NL.NL_LastName)},
                    {Culture_.JP, new FullName(JP.JP_Name, JP.JP_LastName)},{Culture_.SE, new FullName(SE.SE_Name, SE.SE_LastName)},
                    {Culture_.IE, new FullName(IE.IE_Name, IE.IE_LastName)},{Culture_.AU, new FullName(AU.AU_Name, AU.AU_LastName)},
                    {Culture_.CA, new FullName(CA.CA_Name, CA.CA_LastName)},{Culture_.NZ, new FullName(NZ.NZ_Name, NZ.NZ_LastName)},
                    {Culture_.IN, new FullName(IN.IN_Name, IN.IN_LastName)},{Culture_.CN, new FullName(CN.CN_Name, CN.CN_LastName)}
                };
            }

            return CulturalNames[culture_];
        }


        [JsonProperty("AE")]
        public AE AE { get; set; }

        [JsonProperty("GB")]
        public GB GB { get; set; }

    }

    public partial class AE
    {
        [JsonProperty("AE_Name")]
        public string AE_Name { get; set; }

        [JsonProperty("AE_LastName")]
        public string AE_LastName { get; set; }
    }

  

    public partial class GB
    {
        [JsonProperty("GB_Name")]
        public string GB_Name { get; set; }

        [JsonProperty("GB_LastName")]
        public string GB_LastName { get; set; }
    }

}

But one question, is there a way where I can model the dictionary field? @Skydiver , @Sheepings - If you can help in that?
 
Last edited:
What do you mean exactly by "model the dictionary field"? To me that sounds like you simply have to implement IDictionary<TKey, TValue>.

I'm still trying to understand your code above. It's not very clear why you need to load some stuff from JSON, but at the same time you have some hard coded dictionary values.
 
From what I can figure out, your JSON looks like this. Although it looks compact, it's not very friendly for writing code against:
JSON:
{
    "StringResources" : {
        "Culture" : {
            "Cultures" : {
                "Culture_AE" : "United Arab Emirates",
                "Culture_DE" : "Deustch",
                "Culture_FR" : "French",
                "Culture_JP" : "Japanese",
                "Culture_US" : "United States"
            },
            "CulturalName" : {
                "AE" : {
                    "AE_Name" : "Omar",
                    "AE_LastName" : "Ali"
                },
                "DE" : {
                    "DE_Name" : "Hans",
                    "DE_LastName" : "Muller"
                },
                "FR" : {
                    "FR_Name" : "Louis",
                    "FR_LastName" : "Bisset"
                },
                "JP" : {
                    "JP_Name" : "Hiro",
                    "JP_LastName" : "Tanaka"
                },
                "US" : {
                    "US_Name" : "Aaron",
                    "US_LastName" : "Smith"
                }
            }
        }
    }
}

I would suggest restructuring the JSON to be more regular and easier to write code against:
JSON:
{
    "StringResources" : {
        "Cultures" : [
            {
                "Culture" : {
                    "Code" : "AE",
                    "Name" : "United Arab Emirates",
                    "CulturalName" : {
                        "Name" : "Omar",
                        "LastName" : "Ali"
                    }   
                }   
            },
            {
                "Culture" : {
                    "Code" : "DE",
                    "Name" : "Deustch",
                    "CulturalName" : {
                        "Name" : "Hans",
                        "LastName" : "Muller"
                    }   
                }   
            },
            {
                "Culture" : {
                    "Code" : "FR",
                    "Name" : "French",
                    "CulturalName" : {
                        "Name" : "Louis",
                        "LastName" : "Bisset"
                    }   
                }   
            },
            {
                "Culture" : {
                    "Code" : "JP",
                    "Name" : "Japanese",
                    "CulturalName" : {
                        "Name" : "Hiro",
                        "LastName" : "Tanaka"
                    }   
                }   
            },
            {
                "Culture" : {
                    "Code" : "US",
                    "Name" : "United States",
                    "CulturalName" : {
                        "Name" : "Aaron",
                        "LastName" : "Smith"
                    }   
                }   
            }
        ]
    }
}
 
I couldn't sleep so here's some code to muddle through. All of them access a dictionary using a 2 letter country code to get some kind of Culture object that has the details. It should be no surprise that if you store the data in JSON as a dictionary, then it should read back in as a dictionary.

C#:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;

class FullName
{
    public string Name { get; set; }
    public string LastName { get; set; }

    public override string ToString() => $"{Name} {LastName}";
}

class LoadArray
{
    class Culture
    {
        public string Code { get; set; }
        public string Name { get; set; }
        public FullName CulturalName { get; set; }
    }

    class StringResources
    {
        public IList<Culture> Cultures { get; set; }

        [JsonIgnore]
        public IDictionary<string, Culture> Culture => Cultures.ToDictionary(c => c.Code);
    }

    public void Run()
    {
        var jsonString = File.ReadAllText(@"StringResources1.json");
        var jobject = JObject.Parse(jsonString);
        var stringResources = jobject["StringResources"].ToObject<StringResources>();

        Console.WriteLine(stringResources.Culture["JP"].CulturalName);
    }
}

class LoadArray2
{
    class Culture
    {
        public string Name { get; set; }
        public FullName CulturalName { get; set; }
    }

    class StringResources
    {
        public IDictionary<string, Culture> Cultures { get; set; }
    }

    public void Run()
    {
        var jsonString = File.ReadAllText(@"StringResources1.json");
        var jobject = JObject.Parse(jsonString);
        var stringResources = new StringResources()
        {
            Cultures = jobject["StringResources"]
                              ["Cultures"]
                              .ToDictionary(t => t["Code"].ToString(),
                                            t => t.ToObject<Culture>())
        };

        Console.WriteLine(stringResources.Cultures["JP"].CulturalName);
    }
}

class LoadDictionary
{
    class Culture
    {
        public string Name { get; set; }
        public FullName CulturalName { get; set; }
    }

    class StringResources
    {
        public IDictionary<string, Culture> Cultures { get; set; }
    }

    public void Run()
    {
        var jsonString = File.ReadAllText(@"StringResources2.json");
        var jobject = JObject.Parse(jsonString);
        var stringResources = jobject["StringResources"].ToObject<StringResources>();

        Console.WriteLine(stringResources.Cultures["JP"].CulturalName);
    }
}

class Program
{
    static void Main()
    {
        new LoadArray().Run();
        new LoadArray2().Run();
        new LoadDictionary().Run();
    }
}

StringResources1.json:
{
  "StringResources": {
    "Cultures": [
      {
        "Code": "AE",
        "Name": "United Arab Emirates",
        "CulturalName": {
          "Name": "Omar",
          "LastName": "Ali"
        }
      },
      {
        "Code": "DE",
        "Name": "Deustch",
        "CulturalName": {
          "Name": "Hans",
          "LastName": "Muller"
        }
      },
      {
        "Code": "FR",
        "Name": "French",
        "CulturalName": {
          "Name": "Louis",
          "LastName": "Bisset"
        }
      },
      {
        "Code": "JP",
        "Name": "Japanese",
        "CulturalName": {
          "Name": "Hiro",
          "LastName": "Tanaka"
        }
      },
      {
        "Code": "US",
        "Name": "United States",
        "CulturalName": {
          "Name": "Aaron",
          "LastName": "Smith"
        }
      }
    ]
  }
}

StringResources2.json:
{
  "StringResources": {
    "Cultures": {
      "AE": {
        "Name": "United Arab Emirates",
        "CulturalName": {
          "Name": "Omar",
          "LastName": "Ali"
        }
      },
      "DE": {
        "Name": "Deustch",
        "CulturalName": {
          "Name": "Hans",
          "LastName": "Muller"
        }
      },
      "FR": {
        "Name": "French",
        "CulturalName": {
          "Name": "Louis",
          "LastName": "Bisset"
        }
      },
      "JP": {
        "Name": "Japanese",
        "CulturalName": {
          "Name": "Hiro",
          "LastName": "Tanaka"
        }
      },
      "US": {
        "Name": "United States",
        "CulturalName": {
          "Name": "Aaron",
          "LastName": "Smith"
        }
      }
    }
  }
}
 
Yes
What do you mean exactly by "model the dictionary field"? To me that sounds like you simply have to implement IDictionary<TKey, TValue>.

I'm still trying to understand your code above. It's not very clear why you need to load some stuff from JSON, but at the same time you have some hard coded dictionary values.
basically I want to serialise Dictionary maybe like these, and my code is bit complex, where I have few data seaprately "Name" and "Lastname" as per cultures and then I want to add them in dictionary

Now after deserialization, to access dictionary value I have to use singleton so instead of that If i can serialize that dictionary field in json it self so it can be accessed directly

But i'm not able to figure out how do I do that


JSON Class:
namespace Framework.JsonModel
{
    using Framework.Config;
    using Framework.Helpers;
    using Newtonsoft.Json;
    using System.Collections.Generic;
    using System.ComponentModel;

    public class StringResourcesTestData
    {
        public const string jsonFilePath = "JsonData\\Constants\\StringResources.json";
        public static StringResourcesX StringResources { get; set; }

        private StringResourcesTestData()
        {

        }

        public static StringResourcesX Get()
        {
            if(StringResources == null)
                StringResources = JsonHelper
                    .GetTestParams<StringResourcesJson>(ConfigProvider.BuildPath(jsonFilePath))
                    .StringResources;

            return StringResources;
        }
    }

    public partial class StringResourcesJson
    {
        [JsonProperty("StringResources")]
        public StringResourcesX StringResources { get; set; }
    }

    public partial class StringResourcesX
    {
        [JsonProperty("Culture")]
        public Culture Culture { get; set; }

     
    }

   

    public partial class Culture
    {
        [JsonProperty("Cultures")]
        public Cultures Cultures { get; set; }

        [JsonProperty("CulturalName")]
        public CulturalName CulturalName { get; set; }
       
    }

    public partial class CulturalName
    {
        public enum CultureEnum
        {
            GB,
            US,
            IT,
            FR,
            CA,
            DE,
            SE,
            NL,
            NZ,
            AU,
            AE,
            CN,
            JP,
            IE,
            IN,
            ES
        }
        public class FullName
        {
            public string First;
            public string Last;
            public FullName(string first, string last)
            {
                this.First = first;
                this.Last = last;
            }
        }
        public Dictionary<CultureEnum, FullName> CulturalNames;

        public FullName GetName(CultureEnum culture_)
        {
            if (CulturalNames == null)
            {
                CulturalNames = new Dictionary<CultureEnum, FullName>
                {
                    {CultureEnum.GB, new FullName (GB.Name, GB.LastName)},{CultureEnum.US, new FullName(US.Name ,US.LastName)},
                    {CultureEnum.IT, new FullName(IT.Name, IT.LastName)},{CultureEnum.ES, new FullName(ES.Name, ES.LastName)},
                    {CultureEnum.FR, new FullName(FR.Name, FR.LastName)},{CultureEnum.AE, new FullName(AE.Name, AE.LastName)},
                    {CultureEnum.DE, new FullName(DE.Name, DE.LastName)},{CultureEnum.NL, new FullName(NL.Name, NL.LastName)},
                    {CultureEnum.JP, new FullName(JP.Name, JP.LastName)},{CultureEnum.SE, new FullName(SE.Name, SE.LastName)},
                    {CultureEnum.IE, new FullName(IE.Name, IE.LastName)},{CultureEnum.AU, new FullName(AU.Name, AU.LastName)},
                    {CultureEnum.CA, new FullName(CA.Name, CA.LastName)},{CultureEnum.NZ, new FullName(NZ.Name, NZ.LastName)},
                    {CultureEnum.IN, new FullName(IN.Name, IN.LastName)},{CultureEnum.CN, new FullName(CN.Name, CN.LastName)}
                };
            }

            return CulturalNames[culture_];
        }


        [JsonProperty("AE")]
        public CultureNameDetails AE { get; set; }

        [JsonProperty("GB")]
        public CultureNameDetails GB { get; set; }

        [JsonProperty("US")]
        public CultureNameDetails US { get; set; }

        [JsonProperty("CN")]
        public CultureNameDetails CN { get; set; }

        [JsonProperty("IT")]
        public CultureNameDetails IT { get; set; }

        [JsonProperty("ES")]
        public CultureNameDetails ES { get; set; }

        [JsonProperty("FR")]
        public CultureNameDetails FR { get; set; }

        [JsonProperty("DE")]
        public CultureNameDetails DE { get; set; }

        [JsonProperty("NL")]
        public CultureNameDetails NL { get; set; }

        [JsonProperty("SE")]
        public CultureNameDetails SE { get; set; }

        [JsonProperty("IE")]
        public CultureNameDetails IE { get; set; }

        [JsonProperty("AU")]
        public CultureNameDetails AU { get; set; }

        [JsonProperty("CA")]
        public CultureNameDetails CA { get; set; }

        [JsonProperty("NZ")]
        public CultureNameDetails NZ { get; set; }

        [JsonProperty("IN")]
        public CultureNameDetails IN { get; set; }

        [JsonProperty("JP")]
        public CultureNameDetails JP { get; set; }
    }

    public partial class CultureNameDetails
    {
        [JsonProperty("Name")]
        public string Name { get; set; }

        [JsonProperty("LastName")]
        public string LastName { get; set; }
    }

    public partial class Cultures
    {
        [JsonProperty("Culture_UK")]
        public string Culture_UK { get; set; }

        [JsonProperty("Culture_US")]
        public string Culture_US { get; set; }

        [JsonProperty("Culture_CA")]
        public string Culture_CA { get; set; }

        [JsonProperty("Culture_DE")]
        public string Culture_DE { get; set; }

        [JsonProperty("Culture_JP")]
        public string Culture_JP { get; set; }
    }
 
}


JSON Data:
{
  "StringResources": {
    "Culture": {
      "Cultures": {
        "Culture_UK": "en-GB",
        "Culture_US": "en-US",
        "Culture_CA": "en-CA",
        "Culture_DE": "de-DE",
        "Culture_JP": "ja-JP"
      },
      "CulturalName": {
        "AE": {
          "Name": "Abu'l-Fadl",
          "LastName": "Isa"
        },
        "GB": {
          "Name": "Jamie",
          "LastName": "Lanister"
        },
        "US": {
          "Name": "Tyrion",
          "LastName": "Lanister"
        },
        "CN": {
          "Name": "陶",
          "LastName": "致远"
        },
        "IT": {
          "Name": "Clelia",
          "LastName": "Calabrese"
        },
        "ES": {
          "Name": "Sebastián",
          "LastName": "Hinojosa Argüello"
        },
        "FR": {
          "Name": "L'Heureux",
          "LastName": "Boulé"
        },
        "DE": {
          "Name": "Jörg",
          "LastName": "Gärtner"
        },
        "NL": {
          "Name": "Selma",
          "LastName": "Løkkeberg"
        },
        "SE": {
          "Name": "Ekström",
          "LastName": "Åberg"
        },
        "IE": {
          "Name": "Bailey",
          "LastName": "Quinn"
        },
        "AU": {
          "Name": "Lola",
          "LastName": "Patel"
        },
        "CA": {
          "Name": "Max",
          "LastName": "Godfrey"
        },
        "NZ": {
          "Name": "Edward",
          "LastName": "Bevan"
        },
        "IN": {
          "Name": "Anshu",
          "LastName": "Chahal"
        },
        "JP": {
          "Name": "ナルト",
          "LastName": "うずまき"
        }
      }
    }
  }
}

And this is how I currently access


C#:
var StringResourceData = StringResourcesTestData.Get();
            var t1 = StringResourcesTestData.Get().Culture.CulturalName.GetName(Constants.Culture.GB);
            var t2 = StringResourcesTestData.Get().Culture.CulturalName.GetName(Constants.Culture.AE);
 
Last edited:

Latest posts

Back
Top Bottom