2

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; }

}
3
  • Google Newtonsoft.Json Commented Nov 29, 2019 at 3:31
  • .NET BCL also has a DataContractJsonSerializer Commented Nov 29, 2019 at 3:38
  • @zaitsman, I am already using newtonsoft.json. otherwise, there won't be jObject and jToken in my code. although there may be a better way of using them, which I am looking for. Commented Nov 29, 2019 at 3:40

2 Answers 2

4

I am really lost as to what the problem is, but essentially:

public class CustomerList {
  [JsonProperty("custlist")]
   public Customer[] Customers { get; set; }
}

public class Customer
{
    [JsonProperty("cust_name")]
    public string Name { get; set; }

    [JsonProperty("cust_id")]
    public string Id { get; set; }
}

var sample = "{\"custlist\":[{\"cust_name\":\"Vincent\"},{\"cust_id\":\"klq206f3872d08m92t6\"},{\"cust_name\":\"Joyce\"},{\"cust_id\":\"125g1474grx2d03t9dld\"}]}";

var result = JsonConvert.DeserializeObject<CustomerList>(sample).Customers;
// Or!

var dictResult = JsonConvert.DeserializeObject<Dictionary<string, Customer[]>>(sample)["custlist"];

Sign up to request clarification or add additional context in comments.

5 Comments

I try to run your code but it's making exception github.com/anirugu/cslearning/blob/master/q59098442.cs Can you confirm what I am missing here.
"Invalid character after parsing property name. Expected ':' but got: c. Path 'custlist[1]', line 1, position 40."
@AnirudhaGupta try now. Seems when i was copying your sample, some extraneous "" chars got added; i edited the sample and it runs how
@AnirudhaGupta It seems that the original poster had invalid JSON in their JSON string: \"\"cust_id\" -> ""cust_id" Wow. This JSON has a lot of problems, actually.
@zaitsman, My apology, the sample string I posted originally was wrong. I just fixed it. The solution works perfectly. Thanks
3

Looks like it's a JSON object that is stored in a JSON string.

So deserialize it as a string first, then as a list of the correct type. You can do both using JsonConvert.DeserializeObject:

Update: I just realized that the array in the JSON is a property of the JSON object, which I didn't account for here. I don't have time to fix that right now, but I hope you get the idea.

public List<T> Json2List<T>(string s)
{
    string json_object = JsonConvert.DeserializeObject<string>(s);

    return JsonConvert.DeserializeObject<List<T>>(json_object);
}

But I would also look into why the data you're getting is double-serialized like that.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.