Wednesday, September 14, 2016

Convert JSON string to C# object

Convert JSON string to C# object

using System.Windows;

using System.IO;
using System.Text;
using System.Collections.Generic;
using System.Diagnostics;

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

namespace WpfApplication4
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void button_Click(object sender, RoutedEventArgs e)
        {
            string str = "{\"Status\":true,\"ErrArr\":[],\"ErrCount\":0,\"ObjArr\":[],\"Data\":{\"Test\":\"Hello\",\"ItemArr\":[{\"IDItem\":111,\"ItemNum\":\"AA01\",\"ItemName\":\"Computer\"},{\"IDItem\":112,\"ItemNum\":\"AA02\",\"ItemName\":\"Desk\"}]}}";

            MemoryStream jsonSource = new MemoryStream(Encoding.UTF8.GetBytes(str));
            var s = new DataContractJsonSerializer(typeof(RootObject));
            var j = (RootObject)s.ReadObject(jsonSource);

            Debug.WriteLine(str);

            Debug.WriteLine(j.Data.Test);

            for (int i = 0; i < j.Data.ItemArr.Count; i++)
            {
                Debug.WriteLine(j.Data.ItemArr[i].IDItem + "; " + j.Data.ItemArr[i].ItemNum + "; " + j.Data.ItemArr[i].ItemName);
            }
        }
    }


    [DataContract]
    public class ItemArr
    {
        [DataMember]
        public int IDItem { get; set; }

        [DataMember]
        public string ItemNum { get; set; }

        [DataMember]
        public string ItemName { get; set; }
    }

    [DataContract]
    public class Data
    {
        [DataMember]
        public string Test { get; set; }

        [DataMember]
        public List<ItemArr> ItemArr { get; set; }
    }

    [DataContract]
    public class RootObject
    {
        [DataMember]
        public bool Status { get; set; }

        [DataMember]
        public List<object> ErrArr { get; set; }

        [DataMember]
        public int ErrCount { get; set; }

        [DataMember]
        public List<object> ObjArr { get; set; }

        [DataMember]
        public Data Data { get; set; }
    }
}

Reference:

http://json2csharp.com/

No comments: