简体   繁体   English

自动将Json字符串转换为C#对象

[英]Auto Convert Json String to C# Object

I have this string below with '\\t', '\\r' and '\\n' which I need to convert to a valid Json format with a loop so that I can Deserializeto an object without listing the object properties. 我下面有一个带有'\\ t','\\ r'和'\\ n'的字符串,我需要使用循环将其转换为有效的Json格式,这样我才能在不列出对象属性的情况下反序列化为对象。

"Title\\tFirstName\\tLastName\\tAge\\r\\nMr\\tBla bla\\tBla bla\\t25\\r\\nMiss\\tBla bla\\tBla bla\\t35\\r\\n" “标题\\ tFirstName \\ tLastName \\ tAge \\ r \\ nMr \\ tBla bla \\ tBla bla \\ t25 \\ r \\ nMiss \\ tBla bla \\ tBla bla \\ t35 \\ r \\ n”

You can use String.Split method to solve your problem. 您可以使用String.Split方法来解决您的问题。

  • First of all you need to split by \\r\\n - this will give you individual rows with data 首先,您需要除以\\r\\n这将为您提供包含数据的单独行
  • You can loop through these rows and split each of them by \\t symbol - this will give you array of properties 您可以遍历这些行,并用\\t符号将它们分开-这将为您提供属性数组
  • After you have all the "ingredients" - you can build your objects: using dynamic objects new { firstName = arrayData[0], lastName = arrayData[1], ..} , or you can create a new class with all the required properties 在拥有所有“成分”之后,您可以构建对象:使用动态对象new { firstName = arrayData[0], lastName = arrayData[1], ..} ,或者可以创建具有所有必需属性的新类。
  • Last step will be serialize collection of your objects into json - I would recommend Json.NET library for this purpose: http://www.newtonsoft.com/json 最后一步是将您的对象集合序列化为Json.NET为此,我建议使用Json.NET库: http : //www.newtonsoft.com/json

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

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