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

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

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:

  1. {
  2. &quot;Project&quot;: [
  3. {
  4. &quot;ProjectCode&quot;: &quot;001&quot;,
  5. &quot;Groups&quot;: [&quot;Manager&quot;, &quot;Supervisor&quot;, &quot;Validation&quot;, &quot;DocumentReviewer&quot;,&quot;ManagerReviewer&quot;]
  6. },
  7. {
  8. &quot;ProjectCode&quot;: &quot;002&quot;,
  9. &quot;Groups&quot;: [&quot;Manager&quot;, &quot;Supervisor&quot;, &quot;Validation&quot;]
  10. }
  11. ]

}de here

答案1

得分: 1

你可以尝试这段代码

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

you can try this code

  1. string json = JsonConvert.SerializeObject( new
  2. {
  3. Project = list.Select(l =&gt; l.Split(&quot;-&quot;))
  4. .Select(l =&gt; new { Key = l[0], Value = l[2] })
  5. .GroupBy(g =&gt; g.Key, g =&gt; g.Value)
  6. .Select(g =&gt; new { ProjectCode = g.Key, Groups = g })
  7. }, Newtonsoft.Json.Formatting.Indented);
  8. </details>
  9. # 答案2
  10. **得分**: 1
  11. 以下是翻译好的内容:
  12. 使用传统方法而没有任何一行代码。我已经创建了相应的“Model”类来保存您的数据并根据需要对其进行标记,以填充到“Model”类的相应字段中:
  13. Fiddle链接:https://dotnetfiddle.net/XH28FX
  14. ```csharp
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Linq;
  18. using Newtonsoft.Json;
  19. public class Program
  20. {
  21. public static void Main()
  22. {
  23. List<string> input = new List<string>();
  24. input.Add("001-HA-Manager");
  25. input.Add("001-HA-Supervisor");
  26. input.Add("001-HA-Validation");
  27. input.Add("001-HA-DocumentReviewer");
  28. input.Add("001-HA-ManagerReviewer");
  29. input.Add("002-HA-Manager");
  30. input.Add("002-HA-Supervisor");
  31. input.Add("002-HA-Validation");
  32. List<Lookup> lookup = new List<Lookup>();
  33. foreach (var item in input)
  34. {
  35. Lookup lookupitem = new Lookup();
  36. var tokenizeditem = item.Split('-');
  37. lookupitem.ProjectCode = tokenizeditem[0];
  38. lookupitem.Title = tokenizeditem[2];
  39. lookup.Add(lookupitem);
  40. }
  41. //现在按项目代码分组:
  42. var test = from p in lookup
  43. group p.Title by p.ProjectCode into g
  44. select new Project { ProjectCode = g.Key, Groups = g.ToList() };
  45. var customDataObj = new { Project = test };
  46. var jstring = JsonConvert.SerializeObject(customDataObj);
  47. Console.WriteLine(jstring);
  48. }
  49. }
  50. public class Project
  51. {
  52. public string ProjectCode { get; set; }
  53. public List<string> Groups { get; set; }
  54. }
  55. public class Lookup
  56. {
  57. public string ProjectCode { get; set; }
  58. public string Title { get; set; }
  59. }
  60. ```
  61. 输出:`{"Project":[{"ProjectCode":"001","Groups":["Manager","Supervisor","Validation","DocumentReviewer","ManagerReviewer"]},{"ProjectCode":"002","Groups":["Manager","Supervisor","Validation"]}]}`
  62. 在[Jsonlint](https://jsonlint.com/)上验证后:
  63. [![进入图像描述][2]][2]
  64. [2]: https://i.stack.imgur.com/H7hMQ.png
  65. <details>
  66. <summary>英文:</summary>
  67. 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:
  68. Fiddle: https://dotnetfiddle.net/XH28FX
  69. using System;
  70. using System.Collections.Generic;
  71. using System.Linq;
  72. using Newtonsoft.Json;
  73. public class Program
  74. {
  75. public static void Main()
  76. {
  77. List&lt;string&gt; input=new List&lt;string&gt;();
  78. input.Add(&quot;001-HA-Manager&quot;);
  79. input.Add(&quot;001-HA-Supervisor&quot;);
  80. input.Add(&quot;001-HA-Validation&quot;);
  81. input.Add(&quot;001-HA-DocumentReviewer&quot;);
  82. input.Add(&quot;001-HA-ManagerReviewer&quot;);
  83. input.Add(&quot;002-HA-Manager&quot;);
  84. input.Add(&quot;002-HA-Supervisor&quot;);
  85. input.Add(&quot;002-HA-Validation&quot;);
  86. List&lt;Lookup&gt; lookup= new List&lt;Lookup&gt;();
  87. foreach(var item in input)
  88. {
  89. Lookup lookupitem=new Lookup();
  90. var tokenizeditem=item.Split(&#39;-&#39;);
  91. lookupitem.ProjectCode=tokenizeditem[0];
  92. lookupitem.Title=tokenizeditem[2];
  93. lookup.Add(lookupitem);
  94. }
  95. //Now group by:
  96. var test= from p in lookup
  97. group p.Title by p.ProjectCode into g
  98. select new Project { ProjectCode = g.Key, Groups = g.ToList() };
  99. var customDataObj = new { Project = test };
  100. var jstring= JsonConvert.SerializeObject(customDataObj);
  101. Console.WriteLine(jstring);
  102. }
  103. }
  104. public class Project
  105. {
  106. public string ProjectCode {get;set;}
  107. public List&lt;string&gt; Groups {get;set;}
  108. }
  109. public class Lookup
  110. {
  111. public string ProjectCode {get;set;}
  112. public string Title {get;set;}
  113. }
  114. 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;]}]}`
  115. After validating from [Jsonlint][1]:
  116. [![enter image description here][2]][2]
  117. [1]: https://jsonlint.com/
  118. [2]: https://i.stack.imgur.com/H7hMQ.png
  119. </details>
  120. # 答案3
  121. **得分**: 0
  122. 以下是您要翻译的内容:
  123. 1. 创建类
  124. 然后,定义一个构造函数来接收数据,然后分离项目和组,然后对项目进行分组并创建 JSON
  125. 我使用 Newtonsoft.Json Linq
  126. 2. 创建类
  127. ```csharp
  128. public class MyDate
  129. {
  130. public MyDate(string All)
  131. {
  132. this.All = All;
  133. }
  134. public string ProjectCode
  135. {
  136. get { return this.All.Split('-')[0]; }
  137. }
  138. public string Group
  139. {
  140. get { return this.All.Split('-')[2]; }
  141. }
  142. public string All { set; get; }
  143. }
  144. ```
  145. 3. 添加数据
  146. ```csharp
  147. List<MyDate> _li = new List<MyDate>
  148. {
  149. new MyDate("001-HA-Manager"),
  150. new MyDate("001-HA-Validation"),
  151. new MyDate("001-HA-Supervisor"),
  152. new MyDate("001-HA-Validation"),
  153. new MyDate("001-HA-DocumentReviewer"),
  154. new MyDate("001-HA-ManagerReviewer"),
  155. new MyDate("002-HA-Manager"),
  156. new MyDate("002-HA-Supervisor"),
  157. new MyDate("002-HA-Validation")
  158. };
  159. ```
  160. 4. 使用 Linq 进行分组并创建 JSON
  161. ```csharp
  162. var listall = _li
  163. .GroupBy(d => d.ProjectCode)
  164. .Select(g => new {
  165. ProjectCode = g.Key,
  166. Groups = g.Select(d => d.Group)
  167. }).ToList();
  168. var jsonString = "{\"Project\":" + JsonConvert.SerializeObject(listall, Formatting.Indented) + "}";
  169. ```
  170. 请注意,我已经将代码部分保留为原文,只对注释进行了翻译。
  171. <details>
  172. <summary>英文:</summary>
  173. First create class
  174. then ,define a constructor to receive the data and then separate the project and the group And then group the project and create Jason
  175. I use Newtonsoft.Json and Linq
  176. 1.create class
  177. ```
  178. public class MyDate
  179. {
  180. public MyDate(string All)
  181. {
  182. this.All = All;
  183. }
  184. public string ProjectCode
  185. {
  186. get { return this.All.Split(&#39;-&#39;)[0]; }
  187. }
  188. public string Group
  189. {
  190. get { return this.All.Split(&#39;-&#39;)[2]; }
  191. }
  192. public string All { set; get; }
  193. }
  194. ```
  195. 2.Add data
  196. ```
  197. List&lt; MyDate&gt; _li = new List&lt;MyDate&gt;
  198. { new MyDate(&quot;001-HA-Manager&quot;), new MyDate(&quot;001-HA-Validation&quot;),
  199. new MyDate(&quot;001-HA-Supervisor&quot;),
  200. new MyDate(&quot;001-HA-Validation&quot;),
  201. new MyDate(&quot;001-HA-DocumentReviewer&quot;)
  202. ,new MyDate(&quot;001-HA-ManagerReviewer&quot;)
  203. ,new MyDate(&quot;002-HA-Manager&quot;)
  204. ,new MyDate(&quot;002-HA-Supervisor&quot;)
  205. ,new MyDate(&quot;002-HA-Validation&quot;)
  206. };
  207. ```
  208. 3.group by with linq and create json
  209. ```
  210. var listall = _li
  211. .GroupBy(d =&gt; d.ProjectCode)
  212. .Select(g =&gt; new {
  213. ProjectCode = g.Key,
  214. Groups = g.Select(d =&gt; d.Group)
  215. }).ToList();
  216. var jsonString = &quot;{\r\n\&quot;Project\&quot;:&quot; + JsonConvert.SerializeObject(listall , Formatting.Indented) + &quot;}&quot;;
  217. ```
  218. </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:

确定