none
How to use System.Text.Json to parse a nested object. RRS feed

  • Question

  • Hello,
    I want to know how to parse/deserialize a string to an object.
    I have to following data structure and one json string with the data structure:

    public class AccountData
    {
        public int account_id { get; set; }
        public double rate { get; set; }
        public List<object> balance { get; set; }
        public bool account_open { get; set; }
    }
    
    string account_data = 
    @"{""account_id"":123456,""rate"":1.0,""balance"":[""GBP"",10000.0],""account_open"":true}";
    
    I want to write a function to parse the json string (account_data) to an object (class AccountData) using System.Text.Json.
    I can't see good example for this.
    Thanks,

    Thursday, September 26, 2019 12:32 PM

Answers

  • Since System.Text.Json was named:

    using System.Text.Json;
    
    
    string account_data = 
                    @"{""account_id"":123456,""rate"":1.0,""balance"":[""GBP"",10000.0],""account_open"":true}";
    var myobj = JsonSerializer.Deserialize<AccountData>(account_data);
    

    • Marked as answer by zydjohn Thursday, September 26, 2019 7:41 PM
    Thursday, September 26, 2019 1:09 PM

All replies

  • You can use DataContractJsonSerializer

    I pasted as JSON (from [Paste Special]) the string 

    {"account_id":123456,"rate":1.0,"balance":["GBP",10000.0],"account_open":true}

    to generate :

    public class Rootobject
    {
        public int account_id { get; set; }
        public float rate { get; set; }
        public object[] balance { get; set; }
        public bool account_open { get; set; }
    }

    Then a test :

    var json = @"{""account_id"":123456,""rate"":1.0,""balance"":[""GBP"",10000.0],""account_open"":true}";
    using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
    {                   
        DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Rootobject));
        Rootobject ro = (Rootobject)deserializer.ReadObject(ms);                  
        Console.WriteLine(string.Format("account_id : {0}", ro.account_id));
        Console.WriteLine(string.Format("rate : {0}", ro.rate));
        Console.WriteLine(string.Format("account_open : {0}", ro.account_open));
        Console.WriteLine(string.Format("balance : {0}, {1}", ro.balance[0], ro.balance[1]));              
    }

    Thursday, September 26, 2019 1:05 PM
  • Since System.Text.Json was named:

    using System.Text.Json;
    
    
    string account_data = 
                    @"{""account_id"":123456,""rate"":1.0,""balance"":[""GBP"",10000.0],""account_open"":true}";
    var myobj = JsonSerializer.Deserialize<AccountData>(account_data);
    

    • Marked as answer by zydjohn Thursday, September 26, 2019 7:41 PM
    Thursday, September 26, 2019 1:09 PM