简体   繁体   English

将多语言 json 文件解析为 C# 字典

[英]Parse multilingual json file into C# dictionary

How do I read into a C# dictionary, a multilingual json lexicon in the form:如何读入 C# 字典,形式为多语言 json 词典:

[{
  "Top": {
    "de-DE": "Oben",
    "fr-FR": "haut"
  }
},    {
  "Football": {
    "de-DE": "Fußball",
  },
},
{
  "Taxi": {
  }
}]

In the json file there is a key, and for each supported language, a property and value.在 json 文件中有一个键,对于每种支持的语言,都有一个属性和值。 Where the word in the target language is the same as the key, there is no property for that language under that key in the json file.如果目标语言中的单词与键相同,则 json 文件中该键下没有该语言的属性。

At startup we load into a C# dictionary only those entries for the user language.在启动时,我们仅将用户语言的那些条目加载到 C# 字典中。 In this snippet, the dictionary for German should be在这个片段中,德语词典应该是

Top, Oben
Football, Fußball
Taxi, Taxi

In French法语

Top, Haut
Football, Football,
Taxi, Taxi

How do I read the json file into a C# dictionary?如何将 json 文件读入 C# 字典? The dictionary is not huge ... hundreds rather than millions of entries, so performance is not critical.字典并不大......数百而不是数百万个条目,因此性能并不重要。

I assumed your JSON is List of Array我假设你的 JSON 是数组列表

[
  {
    "Top": {
      "de-DE": "Oben",
      "fr-FR": "haut"
    }
  },
  {
    "Football": {
      "de-DE": "Fußball"
    }
  },
  {
    "Taxi": {
    }
  }
]

You can use JsonConvert.DeserializeObject to convert the json to Dictionary您可以使用JsonConvert.DeserializeObject将 json 转换为Dictionary

var results = JsonConvert.DeserializeObject<List<Dictionary<string, object>>>(json);

//DE Dictionary
var deDict = results.SelectMany(x => x).ToDictionary(x => x.Key, x => JObject.Parse(x.Value.ToString())["de-DE"] == null ? "" : JObject.Parse(x.Value.ToString())["de-DE"].ToString());

//FR Dictionary
var frDict = results.SelectMany(x => x).ToDictionary(x => x.Key, x => JObject.Parse(x.Value.ToString())["fr-FR"] == null ? "" : JObject.Parse(x.Value.ToString())["fr-FR"].ToString());

//DE Dictionary     
foreach (var keyvalue in deDict)
{
    Console.WriteLine($"{keyvalue.Key} : {keyvalue.Value}");
}

//FR Dictionary
foreach (var keyvalue in frDict)
{
    Console.WriteLine($"{keyvalue.Key} : {keyvalue.Value}");
}

OUTPUT输出

Top : Oben
Football : Fußball
Taxi :

Top : haut
Football :
Taxi :

The types类型

public class LocalizationInfo : Dictionary<string, string>
{
    public LocalizationInfo() : base( StringComparer.InvariantCultureIgnoreCase ) { }
}

public class LocalizationItem : Dictionary<string, LocalizationInfo>
{ }

public class LocalizationCollection : List<LocalizationItem>
{
    public Dictionary<string, string> GetLocalizedDict( string cultureName )
    {
        if ( cultureName is null )
        {
            throw new ArgumentNullException( nameof( cultureName ) );
        }

        return this
            .Where( e => e.Count == 1 )
            .Select( e => e.First() )
            .ToDictionary( e => e.Key, e => e.Value == null ? e.Key : e.Value.TryGetValue( cultureName, out var localizedValue ) ? localizedValue : e.Key );
    }

    public Dictionary<string, string> GetLocalizedDict( CultureInfo cultureInfo )
    {
        if ( cultureInfo is null )
        {
            throw new ArgumentNullException( nameof( cultureInfo ) );
        }

        return GetLocalizedDict(cultureInfo.Name);
    }

    public Dictionary<string, string> GetLocalizedDict(  )
    {
        return GetLocalizedDict( CultureInfo.CurrentCulture );
    }
}

and the use case和用例

class Program
{
    static readonly string _json =
        "[{" + Environment.NewLine +
        "  \"Top\": {" + Environment.NewLine +
        "    \"de-DE\": \"Oben\"," + Environment.NewLine +
        "    \"fr-FR\": \"haut\"" + Environment.NewLine +
        "  }" + Environment.NewLine +
        "},    {" + Environment.NewLine +
        "  \"Football\": {" + Environment.NewLine +
        "    \"de-DE\": \"Fußball\"" + Environment.NewLine +
        "  }" + Environment.NewLine +
        "}," + Environment.NewLine +
        "{" + Environment.NewLine +
        "  \"Taxi\": {" + Environment.NewLine +
        "  }" + Environment.NewLine +
        "}]";

    static void Main( string[] args )
    {
        var data = JsonSerializer.Deserialize<LocalizationCollection>( _json );

        var frDict = data.GetLocalizedDict( "fr-fr" );
        var deDict = data.GetLocalizedDict( "de-de" );

        var dict = data.GetLocalizedDict();
    }
}

and a live example一个活生生的例子

BTW顺便提一句

I had choosen a structure like this我选择了这样的结构

{
  "Top": {
    "de-DE": "Oben",
    "fr-FR": "haut"
  },
  "Football": {
    "de-DE": "Fußball"
  },
  "Taxi": {}
}

There is no need for an array with objects which only contain a single property.不需要包含仅包含单个属性的对象的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM