0

I'm using newtonsoft.json to (de)serialize json files. I want to seperate my users in a json file currently my json file is something like this :

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

However I want to give them identifiers like this :

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

I want this to find users easier and not having to loop through every user till I find the right one.. Current code :

 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);
Samo_
  • 21
  • 1
  • 5

1 Answers1

1

Your JSON is not formatted correctly but from what I can see this would do what you want.

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

if you don't want the name twice put

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

on the property If the name is not unique in the collection do a

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

And you will get collections as sub items.

Filip Cordas
  • 2,531
  • 1
  • 12
  • 23
  • Oh that's weird, that it's not formatted correctly, I've let newtonsoft make the json for me. But thankyou this is what I needed! – Samo_ Jan 14 '18 at 12:29