Requirement
I am trying to build a function that takes a json string as input. and outputs list of object. The json string is in a similar format to this:
{\"custlist\":[{\"cust_name\":\"Vincent\",\"cust_id\":\"klq:206f387:2d08m92t6\"},{\"cust_name\":\"Joyce\",\"cust_id\":\"125g:1474grx:2d03t9dld\"}]}
My Search
There are plenty of solutions deserialize json array to list of objects, but the array starts at the beginning of the string. i.e. without the \"custlist\": part
If we have \"custlist\": part in the json string, those solutions break.
My Code
Here is my code in C#. It is working, but I had to use regular expression to match the input string. Seems over-complicated. There must be an easier way. Anyone knows, please kindly advise
public void Test()
{
string str = {\"custlist\":[{\"cust_name\":\"Vincent\",\"cust_id\":\"klq:206f387:2d08m92t6\"},{\"cust_name\":\"Joyce\",\"cust_id\":\"125g:1474grx:2d03t9dld\"}]};
List<Customer> list = Json2List<Customer>(str);
foreach (Customer c in list)
{
console.writeline ("name=" + c.cust_name);
console.writeline ("id=" + c.cust_id);
}
}
public List<T> Json2List<T>(string s)
{
string json_listname = Regex.Match(s, "\"" + @"(\w+?)" + "\":").Groups[0].Value;
JObject jObject = JObject.Parse(s);
List<JToken> jTokenList = jObject.GetValue(json_listname).ToList();
List<T> LstT = new List<T>();
foreach (JToken jt in jTokenList)
{
T obj = jt.ToObject<T>();
LstT.Add(obj);
}
return LstT;
}
public class Customer
{
public string cust_name { get; set; }
public string cust_id { get; set; }
}
Newtonsoft.Json