【问题标题】:How to remove the coulmn name in Json in c#如何在C#中删除Json中的列名
【发布时间】:2017-12-06 17:08:43
【问题描述】:

例如这是我的 JSON:

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

如何删除idname

我想要的输出:

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

【问题讨论】:

  • 您的输出不是有效的 JSON..
  • 我假设在输出中你的意思是[ { "1":"Core" }, { "2":"Moderate" } ]
  • 请告诉我们你到目前为止做了什么
  • [ { 1, "核心" }, { 2, "中等" }, { 3, "远程" } ]
  • 我只是从数据库中获取记录并返回列名我想删除它帮助我提前感谢

标签: javascript c# json


【解决方案1】:

你可以这样做:

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

【讨论】:

  • 它在下一行抛出错误' var obj = new JObject { [el["id"].Value()] = el["name"].Value( ) };'错误是无效的初始化成员声明器
  • 也许索引器初始化器是在 C# 7.0 中引入的,而您没有它。尝试在单独的行中初始化。见编辑
【解决方案2】:

这样试试

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

【讨论】:

    【解决方案3】:

    您可以将 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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-01-24
      • 2021-08-07
      • 2021-12-31
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多