【问题标题】:How do I modify a JSON Object in a JSON list?如何修改 JSON 列表中的 JSON 对象?
【发布时间】:2017-08-19 05:45:39
【问题描述】:

我的 JSON 列表如下所示,(其中 Type 3 是 CommandType.Welcome):

[
  {
    "Keyword": "Hello",
    "Type": 0,
    "Message": "World"
  },
  {
    "Keyword": "Hi",
    "Type": 0,
    "Message": "There"
  },
  {
    "Keyword": "Test",
    "Type": 0,
    "Message": "test"
  },
  {
    "Keyword": "Greeting",
    "Type": 3,
    "Message": "Welcome"
  }
]

我当前的方法将从列表中提取正确的对象并修改该对象,但它不会修改列表对象。例如,command.message = message 但是当我序列化列表时它不会合并更改。

    public void SetGreetMessage(string message)
    {
        var leaveGreet = new LeaveGreetService();
        foreach (var command in leaveGreet.CommandList.Where(x => x.Type == CommandType.Welcome))
        {
            command.Message = message;
            dynamic jsonData = JsonConvert.SerializeObject(CommandList, Formatting.Indented);

            File.WriteAllText("Commands.txt", jsonData);
        }
    }

我在网上查看了一些资源,大多数都解析成一个字符串并用字符串修改它。但我想知道是否有可能以某种方式做到这一点。我知道我可以用这种方法向它添加一个新对象,但修改似乎是一项了不起的壮举。

编辑:

using System;

namespace vVvBot.Model
{
    public class CustomCommand
    {
        public string Keyword { get; set; }
        public CommandType Type { get; set; }
        public string Message { get; set; }
    }

    public enum CommandType
    {
        Message,
        Faq,
        Action,
        Welcome,
        Leaving
    }
}

CommandList 是文件中命令对象的列表

【问题讨论】:

  • 最后两行不应该在循环之外吗?
  • CommandList 的类型是什么?它是集合命令对象,命令是 C# 类吗?
  • @HaseebAsif 我已经编辑了我的问题

标签: c# json


【解决方案1】:

我认为您错误地传递了命令参数并且没有生成 json。我已将serializeObject 参数从CommandList 更改为command

public void SetGreetMessage(string message)
    {
        var leaveGreet = new LeaveGreetService();
        foreach (var command in leaveGreet.CommandList.Where(x => x.Type == CommandType.Welcome))
        {
            command.Message = message;
            dynamic jsonData = JsonConvert.SerializeObject(command, Formatting.Indented);

            File.WriteAllText("Commands.txt", jsonData);
        }
    }

【讨论】:

    猜你喜欢
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-06
    • 2016-02-11
    • 1970-01-01
    相关资源
    最近更新 更多