Top / JUNK / DataContractJsonSerializer

using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Net;

namespace ConsoleApp10
{
    class Program
    {
        static void Main(string[] args) {
            string json = @"
                {
	                ""pepolelist"": [
		                {
			                ""name"": ""田中"",
			                ""place"": ""東京"",
			                ""taste"": ""サッカー""
		                },
		                {
			                ""name"": ""佐藤"",
			                ""place"": ""名古屋"",
			                ""taste"": ""野球""
		                },
		                {
			                ""name"": ""鈴木"",
			                ""place"": ""大阪"",
			                ""taste"": ""<バスケ>""
		                }
	                ]
                }
            ";
            var rootObject = ToObject<Rootobject>(json);

            var sb = new StringBuilder();
            sb.AppendLine(@"<HTML>");
            sb.AppendLine(@"<HEAD>");
            sb.AppendLine(@"</HEAD>");
            sb.AppendLine(@"<BODY>");
            sb.AppendLine(@"<TABLE>");
            sb.AppendLine(@"<TBODY>");
            sb.AppendLine(@"<TR>");
            sb.AppendLine(@"<TH>名前</TH>");
            sb.AppendLine(@"<TH>出身</TH>");
            sb.AppendLine(@"<TH>趣味</TH>");
            sb.AppendLine(@"</TR>");
            foreach (var p in rootObject.pepolelist) {
                sb.AppendLine(@"<TR>");
                sb.AppendLine(string.Format(@"<TD>{0}</TD>", WebUtility.HtmlEncode(p.name)));
                sb.AppendLine(string.Format(@"<TD>{0}</TD>", WebUtility.HtmlEncode(p.place)));
                sb.AppendLine(string.Format(@"<TD>{0}</TD>", WebUtility.HtmlEncode(p.taste)));
                sb.AppendLine(@"</TR>");
            }
            sb.AppendLine(@"</TBODY>");
            sb.AppendLine(@"</TABLE>");
            sb.AppendLine(@"</BODY>");
            sb.AppendLine(@"</HTML>");
            File.WriteAllText(@"Z:\test.html", sb.ToString(), Encoding.UTF8);
        }

        public static T ToObject<T>(string json) {
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json))) {
                var serializer = new DataContractJsonSerializer(typeof(T));
                return (T)serializer.ReadObject(ms);
            }
        }

        [DataContract]        
        public class Rootobject
        {
            [DataMember]
            public Pepolelist[] pepolelist { get; set; }
        }

        [DataContract]
        public class Pepolelist
        {
            [DataMember]
            public string name { get; set; }
            [DataMember]
            public string place { get; set; }
            [DataMember]
            public string taste { get; set; }
        }
    }
}



トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   最終更新のRSS
Last-modified: 2019-08-16 (金) 09:40:30 (68d)