【问题标题】:How can I serialize an object and give it an identifier我怎样才能序列化一个对象并给它一个标识符
【发布时间】:2018-01-13 23:58:28
【问题描述】:

我正在使用 newtonsoft.json 来(反)序列化 json 文件。我想将我的用户分隔在一个 json 文件中,目前我的 json 文件是这样的:

[
  {
    "name": "examplename",
    "inviteID": "",
    "inviteCount": "",
    "invited": ""
  },
  {
    "name": "examplename2",
    "inviteID": "",
    "inviteCount": "",
    "invited": ""
  }
]

但是我想给他们这样的标识符:

    [
      "namehere"[
      {      
        "inviteID": "",
        "inviteCount": "",
        "invited": ""
      }
]

我希望这样可以更轻松地找到用户,而不必遍历每个用户,直到找到合适的用户.. 当前代码:

 if(foundinviter == false)
                {
                    User theuser = new User
                    {
                        name = inviterUsername,
                        inviteID = inviteID,
                        inviteCount = inviteCount.ToString(),
                        invited = invited
                    };
                    userslist.Add(theuser);
                }

            }

            string updatedjson = JsonConvert.SerializeObject(userslist, Formatting.Indented);
            File.WriteAllText("InviteData/data.json", updatedjson);

【问题讨论】:

标签: c# json json.net


【解决方案1】:

您的 JSON 格式不正确,但据我所知,这可以满足您的要求。

JsonConvert.SerializeObject(userslist.ToDictionary(k => k.name, v => v),Formatting.Indented)

如果你不想把名字重复两次

[JsonIgnore]
public string name { get; set; }

关于属性 如果名称在集合中不是唯一的,请执行

userslist.GroupBy(i=>i.Name).ToDictionary(k => k.Key, v => v)

你会得到集合作为子项目。

【讨论】:

  • 哦,这很奇怪,它的格式不正确,我让 newtonsoft 为我制作了 json。但是谢谢你,这正是我所需要的!
猜你喜欢
  • 1970-01-01
  • 2011-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多