How to deserialize json string to object list in c# dot

天涯浪子 提交于 2019-11-29 09:31:45

first create another class:

public class SalesTransactions
{
     public List<clsSalesTran> transactions {get;set;}
     public int count{get;set;}
}

Then use,

JsonConvert.DeserializeObject<SalesTransactions>(inputString)
Shibin Sundar

Create a class as below
By creating the list of class 'clsSalesTran' and a variable for 'Count'

Note: JsonProperty is mandatory from your Json String

public class SalesTransactions
{
     [JsonProperty("transactions")]
     public List<clsSalesTran> transactions {get;set;}
     public int count{get;set;}
}

Then you may use this class as below to deserialize

SalesTransactions st = JsonConvert.DeserializeObject<SalesTransactions>(inputString)

Use the Deserialized object as below

double paymentcharge = st.transactions[0].paymentcharge;

To deserialize a string to a List of objects of a type clsSalesTran:

var myList = JsonConvert.DeserializeObject<List<clsSalesTran>>(inputString);
class WeapsCollection
{
    public Dictionary<string, WeaponDetails> Weapons { get; set; }

}

class WeaponList
{
    public WeaponDetails AEK { get; set; }
    public WeaponDetails XM8 { get; set; }
}

class WeaponDetails
{
    public string Name { get; set; }
    public int Kills { get; set; }
    public int Shots_Fired { get; set; }
    public int Shots_Hit { get; set; }
}

class Program  
{
    static void Main(string[] args)
    {
        string json = @"
        {
           'weapons':

                    {
                       'aek':
                            {
                               'name':'AEK-971 Vintovka',
                               'kills':47,
                               'shots_fired':5406,
                               'shots_hit':858
                            },
                       'xm8':
                            {
                               'name':'XM8 Prototype',
                               'kills':133,
                               'shots_fired':10170,
                               'shots_hit':1790
                            },
                    }

        }";

        WeapsCollection weps = JsonConvert.DeserializeObject<WeapsCollection>(json);
        Console.WriteLine(weps.Weapons.First().Value.Shots_Fired);            

        Console.ReadLine();

    }
}

Reply back in case of any issues.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!