0

I am using Json.net for a project I do in C#, and I got lost looking for how to parse my JSON string to Objects.

so in my program I have a class Person that has 3 properties - string Name, int ID, List condition

every time the user adds a person, the program writes it to a file, it looks like this:

{
  "Name": "fsdf",
  "ID": 234234,
  "Conditions": [
    "2",
    "4",
    "6"
  ]
}
{
  "Name": "David",
  "ID": 5555555,
  "Conditions": [
    "2",
    "4",
    "6"
  ]
}

The function I use to add new objects to the file-

public void AddPerson(Person person)
{
    string output = JsonConvert.SerializeObject(person, Formatting.Indented);
    StreamWriter file = new StreamWriter(@"../Data/Persons.json",true);
    file.WriteLine(output);
    file.Close();

}

Now I have a ComboBox and I want to fill it with all the names from the JSON string. and also there is a TextBox where the user inputs the ID number, and I want it to auto complete the input with the IDs that are already existing in the JSON file.

I think a good way is to parse each JSON object in my file to a Person object (in Persons array), then using a foreach loop add all the IDs in to a list which I can access later, and add all the names to the ComboBox.

using Newtonsofts' Json.net - how do I parse each object in the JSON string to a separate Person object in my program?

*I've been looking through the docs and I cant find a solution.. also tried google but found nothing that addresses my problem. *I started coding again after a long time off, and I am a bit new to JSON so I am sorry if my question is super noob :D.

9
  • 2
    Basically, what you've got isn't a valid JSON object. I would suggest changing your code so that each time the user adds a person, it rewrites the whole file as an array of objects, i.e. [ { /* person 1 */ }, { /* person 2 */ }]. Commented May 21, 2016 at 16:19
  • I edit my question to show you the function I use to add the object to the file, please explain me how can I change it to make it valid. Thank you so much for the answer! Commented May 21, 2016 at 16:24
  • 1
    Instead of appending to the file, you could parse it all as a List<Person>, add the new person to the list, then serialize it out as a List<Person>. Commented May 21, 2016 at 16:26
  • 1
    Well, you're trying to parse it as a list... have you read the json.net documentation? You should be able to work this out with a bit of research and experimentation. Commented May 21, 2016 at 17:17
  • 2
    Just use List<Person> as the type argument... Commented May 21, 2016 at 17:24

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.