-2

I'm new to C#, so please bear with me :)

I have a List of persons like this:

List<Person> PersonsList = new List<Person>();

each Person has three properties:

public string Name { get; set; }
public string Number{ get; set; }
public Adress Adress { get; set; }

and I'm filling it from a text-file, now I need to change the list into a JSON file.

var list = Enumerable.Repeat(PersonsList , PersonsList.Count);
  var json =JsonConvert.SerializeObject(list); 

But I know it is not working because I'm not iterating over PersonsList in Enumerable.Repeat

Can you give me a way around plz?

Amir Shahbabaie
  • 1,352
  • 2
  • 14
  • 33
  • 4
    Just `JsonConvert.SerializeObject(PersonList)` is enough in your case. – Manoz Oct 09 '18 at 08:15
  • 1
    `Enumerable.Repeat` will give you an `IEnumerable>` where `List` is repeated `PersonsList.Count` times. Perhaps you just meant `JsonConvert.SerializeObject(PersonsList)`? – ProgrammingLlama Oct 09 '18 at 08:16

4 Answers4

1

Ok, it looks to me like you are using Enumerable.Repeat() wrong. It takes one object, and duplicates it the amount of times specified. So you seem to have made PersonsList.Count number of new PersonsLists...

Is that the problem you are seeing?

Edit: As for a solution. I would just serialize the PersonsList directly. Unless there's something I misunderstood here.

Pumpkim
  • 23
  • 7
1

If I understand you correct you want to serialize the PersonsList to json again? Just use the

var jsonString = JsonConvert.SerializeObject(PersonsList);

Tobias Moe Thorstensen
  • 8,861
  • 16
  • 75
  • 143
1

This is wrong.

var list = Enumerable.Repeat(PersonsList , PersonsList.Count);
var json =JsonConvert.SerializeObject(list); 

You just have to do:

string jsonPersonsList = JsonConvert.SerializeObject(PersonsList); 
Marco Salerno
  • 5,131
  • 2
  • 12
  • 32
1

try this :

var List=JsonConvert.SerializeObject(PersonsList );

Ammar Mousa
  • 48
  • 10