从JSON属性中删除但保留其值

时间:2014-07-25 15:26:23

标签: c# javascript json string properties

我有JSON:

[
  {
    "Position": "ProjectManager",
    "Salary": 2000
  },
  {
    "Position": "BusinessAnalyst",
    "Salary": 2001
  },
  {
    "Position": "TechnicalLead",
    "Salary": 2002
  },
  {
    "Position": "SeniorSoftwareEngineer",
    "Salary": 2003
  },
  {
    "Position": "SoftwareEngineer",
    "Salary": 2004
  },
  {
    "Position": "JuniorSoftwareEngineer",
    "Salary": 2005
  },
  {
    "Position": "UIUXEngineer",
    "Salary": 2006
  },
  {
    "Position": "QALead",
    "Salary": 2007
  },
  {
    "Position": "SeniorQAEngineer",
    "Salary": 2008
  },
  {
    "Position": "QAEngineer",
    "Salary": 2009
  },
  {
    "Position": "JuniorQAEngineer",
    "Salary": 2010
  },
  {
    "Position": "SeniorAutomationEngineer",
    "Salary": 2011
  },
  {
    "Position": "AutomationEngineer",
    "Salary": 2012
  },
  {
    "Position": "JuniorAutomationEngineer",
    "Salary": 2013
  }
]

但我需要将它转换为这个例子:

{
  "ProjectManager": "2000",
    "BusinessAnalyst": "2001",
    "TechnicalLead": "2002",
    "SeniorSoftwareEngineer": "2003",
    "SoftwareEngineer": "2004",
    "JuniorSoftwareEngineer": "2005",
    "UIUXEngineer": "2006",
    "QALead": "2007",
    "SeniorQAEngineer": "2008",
    "QAEngineer": "2009",
    "JuniorQAEngineer": "2010",
    "SeniorAutomationEngineer": "2011",
    "AutomationEngineer": "2012",
    "JuniorAutomationEngineer": "2013"
}

正如你在第二个例子中所看到的,我只有值而没有属性。我怎样才能做到这一点? (Currentrly我的想法是将Json解析为字符串并删除所有匹配“Position:”或“Salary:”的标记)

2 个答案:

答案 0 :(得分:2)

你不需要这么多东西。 我可以提到一种方法。

让你的json一个是probjson和结果asresjson

var arr=new [];
var res=new { arr }
    for(var i in probjson.length){

var position=probjson[i].Position;
var salary=probjson[i].Salary;

var v = new { position=salary  }
res.arr.add(V);

}

这不是一个完整的

试着想出一个主意。 thankz

答案 1 :(得分:0)

一种方法是迭代数组中的每个对象并填充字典:

// Using JSON.NET you can deserialize the JSON array as an enumerable 
// of dynamically-typed objects (i.e. your array)
IEnumerable<dynamic> employees = JsonConvert
                                   .DeserializeObject<IEnumerable<dynamic>>
                                   (
                                       jsonText
                                   );

Dictionary<string, object> values = new Dictionary<string, object>();

foreach(dynamic employee in employees) 
{
    values.Add((string)employee.Position, (object)employee.Salary);
}

// .NET dictionaries are deserialized into JSON objects!
string convertedJson = JsonConvert.SerializeObject(values);

Check a working sample on .NET Fiddle!

更新

如果你想要一个基于LINQ扩展方法的单行解决方案,那么:

string convertedJson = JsonConvert.SerializeObject
(
    JsonConvert.DeserializeObject<IEnumerable<dynamic>>(jsonText)
        .ToDictionary(employee => employee.Position, employee => employee.Salary)
);