例如,我有一串文字
"{"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
答案 0 :(得分:2)
提供有效的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