简体   繁体   中英

Parse Json to class with C#

I have a Json file with following structure

{"status":"OK","masterlist":{"session":{"session_id":1621,"session_name":"Regular Session 2019"}

,"0":{"bill_id":001,"number":"2","change_hash":"xxxxxx","url":"xxxx","status_date":"2019-03-05","status":"1","last_action_date":"2019-03-05","last_action":"action","title":xxx,"description":xxxx"},

"2":{"bill_id":001,"number":"2","change_hash":"xxxxxx","url":"xxxx","status_date":"2019-03-05","status":"1","last_action_date":"2019-03-05","last_action":"action","title":xxx,"description":xxxx"},

"3":{"bill_id":001,"number":"2","change_hash":"xxxxxx","url":"xxxx","status_date":"2019-03-05","status":"1","last_action_date":"2019-03-05","last_action":"action","title":xxx,"description":xxxx"},

"4":{"bill_id":001,"number":"2","change_hash":"xxxxxx","url":"xxxx","status_date":"2019-03-05","status":"1","last_action_date":"2019-03-05","last_action":"action","title":xxx,"description":xxxx"},

I'm trying to put the contents to list of class like this:

public class LegiBill
    {
        public string bill_id;
        public string number;
        public string change_hash;
        public string url;
        public string status_date;
        public string last_action_date;
        public string last_action;
        public string title;
        public string description;
    }

I'm using Newtonsoft.Jason with following code:

public static T ReadFromJsonStr<T>(string str) where T : new()
  {
   TextReader reader = null;
     try
      {
       return JsonConvert.DeserializeObject<T>(str);
      }
     finally
      {
       if (reader != null)
        reader.Close();
      }
  }

I don't have any problem with reading and parsing! I just don't know how to put the main contents which have labels like "0","1","2","3",.... to list of LegiBill like List<LegiBill> .

Thank you in advance.

If you cannot change json. You can do something like this inside ReadFromJsonStr method

public static List<LegiBill> ReadFromJsonStr(string str)
{
    var parsedObject = JObject.Parse(str);
    var popupJson = parsedObject["masterlist"].ToString();
    var popupObj = JsonConvert.DeserializeObject<Dictionary<string, LegiBill>>(popupJson);

    var filteredList = popupObj.Where(kvp => kvp.Key.Equals("session") == false).Select(x=>x.Value).ToList();
    List<LegiBill> legiBills = new List<LegiBill>(filteredList);

    foreach (var legiBill in filteredList)
    {
        if (legiBill != null)
        {
            legiBills.Add(legiBill);
        }
    }

    return legiBills;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM