Reputation: 323
I have a string of text, for example
"{"Date": 01/01/2019, "0": "John", "1": "Jack", "3": "Tom", "4": "Will", "5": "Joe"}"
Also, I have an entity
public class demo {
public string firstValue { get; set; }
public string secondValue { get; set; }
}
Is it possible to transform the string of text into the entity? For example,
"Date"
goes to firstValue
01/01/2019
goes to secondValue
"0"
goes to firstValue
"John"
goes to secondValue
Upvotes: 0
Views: 74
Reputation: 4334
Provided it's valid Json and the 01/01/2019 string is in quotes, this works:
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);
}
Writes:
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
Upvotes: 2