如何在c#中删除Json中的coulmn名称

时间:2017-12-06 17:08:43

标签: javascript c# json

例如,这是我的JSON:

[
   {
      "id":1,
      "name":"Core"
   },
   {
      "id":2,
      "name":"Moderate"
   },
   {
      "id":3,
      "name":"Remote"
   }
]

如何删除idname

我想要的输出:

[
  {
    "1":"Core"
  },
  {
    "2":"Moderate"
  },
  {
    "3":"Remote"
  }
]

3 个答案:

答案 0 :(得分:0)

你可以这样做:

            JArray arr = JArray.Parse(json);

            foreach (var el in arr.ToList())
            {
              var obj = new JObject();
              obj[el["id"].Value<string>()] = el["name"].Value<string>();
              el.Replace(obj);
            }

            var res = arr.ToString();

答案 1 :(得分:0)

试试这个

var objs = new[]
{
    new {Id = 1, Name = "Core"},
    new {Id = 2, Name = "Moderate"},
    new {Id = 3, Name = "Remote"},
};

var json1 = JsonConvert.SerializeObject(objs);
Console.WriteLine(json1);

var dict = objs.ToDictionary(k => k.Id.ToString(), v => v.Name);

var json2 = JsonConvert.SerializeObject(dict);
Console.WriteLine(json2);

答案 2 :(得分:-1)

您可以将json字符串反序列化为对象(MyType)并覆盖ToString()方法

public void YourMethod(){
   string json = ...; // your json string 
   List<MyType> myType = JsonConvert.DeserializeObject<List<MyType>>(json);
   var output = string.Join(", ", myType);
}

public class MyType
{
    public int Id
    {
        get;
        set;
    }

    public string Name{
        get;
        set;
    }

    public override string ToString()
    {
        return string.Format("{0}:{1}", Id.ToString(), Name);
    }
}