【问题标题】:Adding a dictionary to an array in an existing json file将字典添加到现有 json 文件中的数组
【发布时间】:2021-03-06 05:33:44
【问题描述】:

我有一个本地 json 文件,我希望能够使用表单中的数据条目将新字典添加到文件中的现有数组中。
IE。 转这个:

[
    {
    "name": "Product1",
    "type": "Drink",
    "costS": 2.5,
    "costB": 2.4,
    "amount": "none",
    "info": "keep cold"
    }
]

进入:

[
    {
    "name": "Product1",
    "type": "Drink",
    "costS": "2.5",
    "costB": "2.4",
    "amount": "none",
    "info": "keep cold"
    }
    {"name": "Product2",
    "type": "Food",
    "costS": "2.8",
    "costB": "4",
    "amount": "34",
    "info": "keep hot"
    }
]

其中每个值都来自一个表单元素(“name”值来自 txtName,“type”值来自 txtType,等等)。 到目前为止,我已经尝试调整来自 this postthis post 的答案,但无济于事。

我对 c# 非常陌生,所以如果答案可以解释到至少很小的深度,我将不胜感激。任何回复都表示赞赏。

【问题讨论】:

  • 这在这个网站上可能不是一个很好的问题,因为它的意思是“有人可以为我写这段代码”。你在哪个部分有问题?将 JSON 反序列化为数组/列表?添加一个对象?将数据序列化回来?

标签: c# json


【解决方案1】:

您可以使用NewtonSoft.Json 来执行此操作。首先,将 JSON 反序列化为 List<Example>,然后将该项目添加到此列表中。最后你可以将List<Example>序列化为string

var list = JsonConvert.DeserializeObject<List<Example>>(json);
Example example = new Example();
example.name = "Product2";
example.info = "keep hot";
example.amount = "34";
example.costB = "4";
example.costS = "2.8";
example.type = "Food";
list.Add(example);

string output = JsonConvert.SerializeObject(list);

public class Example
{
    public string name { get; set; }
    public string type { get; set; }
    public string costS { get; set; }
    public string costB { get; set; }
    public string amount { get; set; }
    public string info { get; set; }
}

【讨论】:

  • @Greefin 享受你的一天 :)
猜你喜欢
  • 1970-01-01
  • 2018-05-31
  • 2015-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-19
相关资源
最近更新 更多