【问题标题】:Create dynamic object hierarchy for Json serialization via Linq通过 Linq 为 Json 序列化创建动态对象层次结构
【发布时间】:2015-07-16 14:23:49
【问题描述】:

给定一个数据库结构:

| Context | Resource | TypeCode | Value               |
|---------|----------|----------|---------------------|
| Home    | Header   |          | Welcome to the site |
| Home    | Footer   |          | copyright company   |
| Error 1 |          |          | Error!              |
| UPC     | 55       | Name     | Product             |
| UPC     | 55       | Weight   | 10                  |

我需要能够生成这个 Json:

{
  "Home": {
    "Header": "Welcome to the site",
    "Footer": "copyright company"
  },
  "Error1": "Error!",
  "UPC": {
    "55": {
      "Name": "Product",
      "Weight": "10"
    }
  }
}

我将使用它来将翻译提供给 angular-translate。值已设置为目标语言的值。我见过这种类型的序列化的各种示例,但它们都假定目标值的深度是一致的。

【问题讨论】:

    标签: c# json asp.net-mvc linq


    【解决方案1】:

    试试这样的东西

    List<List<string>> a = /*parse ur data to this*/;
    foreach(var pa in a){
      dynamic r = getDynamicObject(pa /*List<string>*/);
      string jsonString = Newtonsoft.Json.SerializeObject(r);
      /*you might have ur string*/
    }
    
    /*separate function*/
    GetDynamicObject(IEnumerable<string> a){
     dynamic r = new ExpandoObject();
     if(a.count > 2){
      return (r as Dictionary<string,  object>).Add(a.First(), GetDynamicObject(a.Skip(1)));
      } 
      else {
        return (r as Dictionary<string,  object>).Add(a.First(), a.Last());
     }
    }
    

    注意:-我在这里写的这段代码可能只包含编译时错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-27
      • 2016-01-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多