从JSON属性中删除,但保留它们的值

本文关键字:保留 JSON 属性 删除 | 更新日期: 2023-09-27 18:15:06

我有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"
}

正如你在第二个例子中看到的,我只有值,没有属性。我该怎么做呢?(目前我的想法是将Json解析为字符串并删除与"Position:"或"Salary:"匹配的所有令牌)

从JSON属性中删除,但保留它们的值

你不需要做那么多事情。我可以提一个方法。

让你的json一个是probjson和result 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

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

// 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);

在。net Fiddle上检查一个工作示例!

更新

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

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