简体   繁体   English

从 C# 中的对象列表中获取 JSON 文件

[英]getting a JSON file from a list of Objects in C#

I'm new to C#, so please bear with me :)我是 C# 的新手,所以请耐心等待:)

I have a List of persons like this:我有一个像这样的人名单:

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

each Person has three properties:每个 Person 具有三个属性:

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.我从文本文件中填充它,现在我需要将列表更改为 JSON 文件。

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但我知道它不起作用,因为我没有在 Enumerable.Repeat 中迭代PersonsList

Can you give me a way around plz?你能给我一个解决方法吗?

Ok, it looks to me like you are using Enumerable.Repeat() wrong.好的,在我看来,您使用 Enumerable.Repeat() 是错误的。 It takes one object, and duplicates it the amount of times specified.它需要一个对象,并按照指定的次数复制它。 So you seem to have made PersonsList.Count number of new PersonsLists...所以你似乎已经使 PersonsList.Count 新 PersonsLists 的数量...

Is that the problem you are seeing?这是你看到的问题吗?

Edit: As for a solution.编辑:至于解决方案。 I would just serialize the PersonsList directly.我会直接序列化 PersonsList 。 Unless there's something I misunderstood here.除非我在这里误解了什么。

If I understand you correct you want to serialize the PersonsList to json again?如果我理解你是正确的,你想再次将PersonsList序列PersonsList json 吗? Just use the只需使用

var jsonString = JsonConvert.SerializeObject(PersonsList); var jsonString = JsonConvert.SerializeObject(PersonsList);

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); 

try this :尝试这个 :

var List=JsonConvert.SerializeObject(PersonsList ); var List=JsonConvert.SerializeObject(PersonsList);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM