c# - 是否可以将此字符串放入对象中?
问题描述
我有一串文本,例如
"{"Date": 01/01/2019, "0": "John", "1": "Jack", "3": "Tom", "4": "Will", "5": "Joe"}"
另外,我有一个实体
public class demo {
public string firstValue { get; set; }
public string secondValue { get; set; }
}
是否可以将文本字符串转换为实体?例如,
"Date"
去firstValue
01/01/2019
去secondValue
"0"
去firstValue
"John"
去secondValue
解决方案
如果它是有效的 Json 并且 01/01/2019 字符串在引号中,则此方法有效:
class demo
{
public string firstValue { get; set; }
public string secondValue { get; set; }
}
string json = "{\"Date\": \"01/01/2019\", \"0\": \"John\", \"1\": \"Jack\", \"3\": \"Tom\", \"4\": \"Will\", \"5\": \"Joe\"}";
var obj = (Newtonsoft.Json.Linq.JObject)JsonConvert.DeserializeObject(json);
List<demo> children = obj.Children().Select(c => new demo()
{
firstValue = ((Newtonsoft.Json.Linq.JProperty)c).Name,
secondValue = ((Newtonsoft.Json.Linq.JProperty)c).Value.ToString()
}).ToList();
foreach (var ch in children)
{
Console.WriteLine("firstValue: {0}, secondValue: {1}", ch.firstValue, ch.secondValue);
}
写道:
firstValue: Date, secondValue: 01/01/2019
firstValue: 0, secondValue: John
firstValue: 1, secondValue: Jack
firstValue: 3, secondValue: Tom
firstValue: 4, secondValue: Will
firstValue: 5, secondValue: Joe
推荐阅读
- while-loop - 从具有边界的最近点创建线网络
- xamarin.forms - XAMARIN FORM:如何将消息发送到特定数量的 watsapp
- ios - Swift-4:如何使用带有“Content-Type”的 URLSession 中的参数的 POST 请求获取数据:“application/x-www-form-urlencoded”
- php - 如何访问docker nginx上的其他目录
- laravel - Laravel Nova - BelongsToMany 关系的选择下拉列表中缺少标签
- ruby-on-rails - Rails 模型回调(创建/更新后)attribute_was not working
- javascript - 使用单个索引定位多维数组中的项目
- flutter - Flutter - 通过 HTTP Post 发送 Json
- javascript - 除以 0 时的 JavaScript 计算器
- python - 使用 next() 读取文本文件之前的 StopIteration 错误