c# – JSON.NET – 使用List进行对象更新

有人可以建议一种更新Cheese.Producers列表中的项目的方法吗?

我有以下课程:

class Producer
{
    public string Name { get; set; }
    public int Rating { get; set; }

    public Producer()
    {
    }

    public Producer(string name, int rating)
    {
        Name = name;
        Rating = rating;
    }
}

class Cheese
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string Taste { get; set; }
    public List<Producer> Producers { get; set; }

    public Cheese()
    {
        Producers = new List<Producer>();
    }

    public Cheese(string name, int age)
    {
        Name = name;
        Age = age;
        Producers = new List<Producer>();
    }

    public Cheese(string name, int age, string taste)
    {
        Name = name;
        Age = age;
        Taste = taste;
        Producers = new List<Producer>();
    }
}

在主代码中,我有一个对象(gouda),我想根据从文件中读取的JSON进行更新.

static void Main(string[] args)
{
    Producer prod1 = new Producer("prod1", 5);
    Producer prod2 = new Producer("prod2", 6);
    Producer prod3 = new Producer("prod3", 7);

    Cheese gouda = new Cheese("Gouda", 5, "Mild");
    gouda.Producers.Add(prod1);
    gouda.Producers.Add(prod2);
    gouda.Producers.Add(prod3);

    string propertiesToBeAdded = File.ReadAllText("properties.txt");
    JsonSerializerSettings jsonSerializerSettings = new JsonSerializerSettings
    {
        ObjectCreationHandling = ObjectCreationHandling.Reuse
    };
    JsonConvert.PopulateObject(propertiesToBeAdded, gouda, jsonSerializerSettings);
}

JSON更新文件:

{
  "Name": "Hard Blue",
  "Taste": "Sharp",
  "Producers": [
    {
      "Name": "prod1",
      "Rating": 100
    },
    {
      "Name": "prod3",
      "Rating": 300
    }
  ]
}

主要问题是,当调用PopulateObject时,不会更新Producers列表项,而是添加2个新成员.其他领域似乎工作得很好.
有什么建议?

最佳答案 试试这个:

                Producer prod1 = new Producer("prod1", 5);
                Producer prod2 = new Producer("prod2", 6);
                Producer prod3 = new Producer("prod3", 7);

                Cheese gouda = new Cheese("Gouda", 5, "Mild");
                gouda.Producers.Add(prod1);
                gouda.Producers.Add(prod2);
                gouda.Producers.Add(prod3);

                var propertiesToBeAdded = File.ReadAllText(@"C:\json path");

                var settings = new JsonMergeSettings
                {
                    MergeArrayHandling = MergeArrayHandling.Merge
                };

                var o1 = JObject.Parse(JsonConvert.SerializeObject(gouda));

                o1.Merge(JObject.Parse(propertiesToBeAdded), settings);

                var o = o1.ToString();

你需要稍微改变你的JSON格式:

{
  'Name': 'Hard Blue',
  'Taste': 'Sharp',
  'Producers': [
    {
      'Name': 'prod1',
      'Rating': 100
    },
    {

    },
    {
      'Name': 'prod3',
      'Rating': 300
    }
  ]
}

开始了:

希望这可以帮助.

点赞