如何将 List<string> 转换为 C# 中的 JSON 格式

huangapple go评论77阅读模式
英文:

How to convert List<string> to JSon format in C#

问题

我有一个包含以下项目的字符串列表:

  • 001-HA-Manager
  • 001-HA-Supervisor
  • 001-HA-Validation
  • 001-HA-DocumentReviewer
  • 001-HA-ManagerReviewer
  • 002-HA-Manager
  • 002-HA-Supervisor
  • 002-HA-Validation

我需要将这些项目转换成以下的JSON格式:

{
"Project": [
{
"ProjectCode": "001",
"Groups": ["Manager", "Supervisor", "Validation", "DocumentReviewer", "ManagerReviewer"]
},
{
"ProjectCode": "002",
"Groups": ["Manager", "Supervisor", "Validation"]
}
]
}

英文:

I have a List of string that contains the below items:

  • 001-HA-Manager
  • 001-HA-Supervisor
  • 001-HA-Validation
  • 001-HA-DocumentReviewer
  • 001-HA-ManagerReviewer
  • 002-HA-Manager
  • 002-HA-Supervisor
  • 002-HA-Validation

I need to those item on the below JSON format:

{
&quot;Project&quot;: [
  {
    &quot;ProjectCode&quot;: &quot;001&quot;,
	&quot;Groups&quot;: [&quot;Manager&quot;, &quot;Supervisor&quot;, &quot;Validation&quot;, &quot;DocumentReviewer&quot;,&quot;ManagerReviewer&quot;]
  },
  {
     &quot;ProjectCode&quot;: &quot;002&quot;,
	 &quot;Groups&quot;: [&quot;Manager&quot;, &quot;Supervisor&quot;, &quot;Validation&quot;]
	}
]

}de here

答案1

得分: 1

你可以尝试这段代码

    string json = JsonConvert.SerializeObject( new
	{
		Project = list.Select(l => l.Split("-"))
				  .Select(l => new { Key = l[0], Value = l[2] })
				  .GroupBy(g => g.Key, g => g.Value)
				  .Select(g => new { ProjectCode = g.Key, Groups = g })
	}, Newtonsoft.Json.Formatting.Indented);
英文:

you can try this code

    string json = JsonConvert.SerializeObject( new
{
Project = list.Select(l =&gt; l.Split(&quot;-&quot;))
.Select(l =&gt; new { Key = l[0], Value = l[2] })
.GroupBy(g =&gt; g.Key, g =&gt; g.Value)
.Select(g =&gt; new { ProjectCode = g.Key, Groups = g })
}, Newtonsoft.Json.Formatting.Indented);
</details>
# 答案2
**得分**: 1
以下是翻译好的内容:
使用传统方法而没有任何一行代码。我已经创建了相应的“Model”类来保存您的数据并根据需要对其进行标记,以填充到“Model”类的相应字段中:
Fiddle链接:https://dotnetfiddle.net/XH28FX
```csharp
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
List<string> input = new List<string>();
input.Add("001-HA-Manager");
input.Add("001-HA-Supervisor");
input.Add("001-HA-Validation");
input.Add("001-HA-DocumentReviewer");
input.Add("001-HA-ManagerReviewer");
input.Add("002-HA-Manager");
input.Add("002-HA-Supervisor");
input.Add("002-HA-Validation");
List<Lookup> lookup = new List<Lookup>();
foreach (var item in input)
{
Lookup lookupitem = new Lookup();
var tokenizeditem = item.Split('-');
lookupitem.ProjectCode = tokenizeditem[0];
lookupitem.Title = tokenizeditem[2];
lookup.Add(lookupitem);
}
//现在按项目代码分组:
var test = from p in lookup
group p.Title by p.ProjectCode into g
select new Project { ProjectCode = g.Key, Groups = g.ToList() };
var customDataObj = new { Project = test };
var jstring = JsonConvert.SerializeObject(customDataObj);
Console.WriteLine(jstring);
}
}
public class Project
{
public string ProjectCode { get; set; }
public List<string> Groups { get; set; }
}
public class Lookup
{
public string ProjectCode { get; set; }
public string Title { get; set; }
}
```
输出:`{"Project":[{"ProjectCode":"001","Groups":["Manager","Supervisor","Validation","DocumentReviewer","ManagerReviewer"]},{"ProjectCode":"002","Groups":["Manager","Supervisor","Validation"]}]}`
在[Jsonlint](https://jsonlint.com/)上验证后:
[![进入图像描述][2]][2]
[2]: https://i.stack.imgur.com/H7hMQ.png
<details>
<summary>英文:</summary>
Using a traditional approach without any one liners. I have created corresponding `Model` classes to hold your data and the tokenize it as required to fill out the respective fields into the `Model` class:
Fiddle: https://dotnetfiddle.net/XH28FX
using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
public class Program
{
public static void Main()
{
List&lt;string&gt; input=new List&lt;string&gt;();
input.Add(&quot;001-HA-Manager&quot;);
input.Add(&quot;001-HA-Supervisor&quot;);
input.Add(&quot;001-HA-Validation&quot;);
input.Add(&quot;001-HA-DocumentReviewer&quot;);
input.Add(&quot;001-HA-ManagerReviewer&quot;);
input.Add(&quot;002-HA-Manager&quot;);
input.Add(&quot;002-HA-Supervisor&quot;);
input.Add(&quot;002-HA-Validation&quot;);
List&lt;Lookup&gt; lookup= new List&lt;Lookup&gt;();
foreach(var item in input)
{
Lookup lookupitem=new Lookup();
var tokenizeditem=item.Split(&#39;-&#39;);
lookupitem.ProjectCode=tokenizeditem[0];
lookupitem.Title=tokenizeditem[2];
lookup.Add(lookupitem);	
}
//Now group by:
var test= from p in lookup
group p.Title by p.ProjectCode into g
select new Project { ProjectCode = g.Key, Groups = g.ToList() };
var customDataObj = new { Project = test };
var jstring= JsonConvert.SerializeObject(customDataObj);
Console.WriteLine(jstring);	
}
}
public class Project
{
public string ProjectCode {get;set;}
public List&lt;string&gt; Groups {get;set;}
}
public class Lookup
{
public string ProjectCode {get;set;}
public string Title {get;set;}
}
Output: `{&quot;Project&quot;:[{&quot;ProjectCode&quot;:&quot;001&quot;,&quot;Groups&quot;:[&quot;Manager&quot;,&quot;Supervisor&quot;,&quot;Validation&quot;,&quot;DocumentReviewer&quot;,&quot;ManagerReviewer&quot;]},{&quot;ProjectCode&quot;:&quot;002&quot;,&quot;Groups&quot;:[&quot;Manager&quot;,&quot;Supervisor&quot;,&quot;Validation&quot;]}]}`
After validating from [Jsonlint][1]:
[![enter image description here][2]][2]
[1]: https://jsonlint.com/
[2]: https://i.stack.imgur.com/H7hMQ.png
</details>
# 答案3
**得分**: 0
以下是您要翻译的内容:
1. 创建类
然后,定义一个构造函数来接收数据,然后分离项目和组,然后对项目进行分组并创建 JSON。
我使用 Newtonsoft.Json 和 Linq。
2. 创建类
```csharp
public class MyDate
{
public MyDate(string All)
{
this.All = All;
}
public string ProjectCode
{
get { return this.All.Split('-')[0]; }
}
public string Group
{
get { return this.All.Split('-')[2]; }
}
public string All { set; get; }
}
```
3. 添加数据
```csharp
List<MyDate> _li = new List<MyDate> 
{ 
new MyDate("001-HA-Manager"), 
new MyDate("001-HA-Validation"),
new MyDate("001-HA-Supervisor"),
new MyDate("001-HA-Validation"),
new MyDate("001-HA-DocumentReviewer"),
new MyDate("001-HA-ManagerReviewer"),
new MyDate("002-HA-Manager"),
new MyDate("002-HA-Supervisor"),
new MyDate("002-HA-Validation")
};
```
4. 使用 Linq 进行分组并创建 JSON
```csharp
var listall = _li
.GroupBy(d => d.ProjectCode)
.Select(g => new {
ProjectCode = g.Key,
Groups = g.Select(d => d.Group)
}).ToList();
var jsonString = "{\"Project\":" + JsonConvert.SerializeObject(listall, Formatting.Indented) + "}";
```
请注意,我已经将代码部分保留为原文,只对注释进行了翻译。
<details>
<summary>英文:</summary>
First create class 
then ,define a constructor to receive the data and then separate the project and the group And then  group the project and create Jason
I use Newtonsoft.Json and Linq
1.create class 
```
public class MyDate
{
public MyDate(string All)
{
this.All = All;
}
public string ProjectCode
{
get { return this.All.Split(&#39;-&#39;)[0]; }
}
public string Group
{
get { return this.All.Split(&#39;-&#39;)[2]; }
}
public string All { set; get; }
}
```
2.Add data
```
List&lt; MyDate&gt; _li = new List&lt;MyDate&gt; 
{ new MyDate(&quot;001-HA-Manager&quot;), new MyDate(&quot;001-HA-Validation&quot;),
new MyDate(&quot;001-HA-Supervisor&quot;),
new MyDate(&quot;001-HA-Validation&quot;),
new MyDate(&quot;001-HA-DocumentReviewer&quot;)
,new MyDate(&quot;001-HA-ManagerReviewer&quot;) 
,new MyDate(&quot;002-HA-Manager&quot;) 
,new MyDate(&quot;002-HA-Supervisor&quot;)
,new MyDate(&quot;002-HA-Validation&quot;)
};
```
3.group by with linq and create json
```
var listall = _li
.GroupBy(d =&gt; d.ProjectCode)
.Select(g =&gt; new {
ProjectCode = g.Key,
Groups = g.Select(d =&gt; d.Group)
}).ToList();
var jsonString = &quot;{\r\n\&quot;Project\&quot;:&quot; + JsonConvert.SerializeObject(listall , Formatting.Indented) + &quot;}&quot;;
```
</details>

huangapple
  • 本文由 发表于 2023年5月18日 01:32:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/76274760.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定