跟小D每日学口语

通用Json的处理办法

1、Json的格式:

  • 对象{"name": "value", "name1": "value1"}
  • 对象包含对象数组{"name": "value", "name1": "value1","name3":[{"name4":"value4"},{"name5":"value5"}]}
  • 对象数组[{"name": "value", "name1": "value1"},{"name2": "value2", "name3": "value3"}]

2、通用处理Json对象的C#类:DataContractJsonSerializer,命名空间:System.Runtime.Serialization.Json;

3、用一个控制台来显示,代码如下:

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;

 

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person { name = "LiLei", age = 12, skillArr = new[] { "C#", "Java" } };
            Person p2 = new Person { name = "Jim", age = 13, skillArr = new[] { "ASP.NET", "Javascript" }, friends = new List<Person> { p1 } };
            string p1Str = JsonHelp.strJson<Person>(p1);
            string p2Str = JsonHelp.strJson<Person>(p2);
            string p3Str = JsonHelp.strJson<List<Person>>(new List<Person> { p1, p2 });
            Console.WriteLine(p1Str);
            Console.WriteLine(p2Str);
            Console.WriteLine(p3Str);
            Person pObj1 = JsonHelp.Parse<Person>(p1Str);
            Console.WriteLine(pObj1.GetType().ToString());
            Person pObj2 = JsonHelp.Parse<Person>(p2Str);
            Console.WriteLine(pObj2.GetType().ToString());
            List<Person> pObj3 = JsonHelp.Parse<List<Person>>(p3Str);
            Console.WriteLine(pObj3.GetType().ToString());
            Console.ReadLine();
        }
    }
    [DataContract]
    internal class Person
    {
        [DataMember]
        public string name { get; set; }
        [DataMember]
        public int age { get; set; }
        [DataMember]
        public string[] skillArr { get; set; }
        [DataMember]
        public List<Person> friends { get; set; }
    }
    internal static class JsonHelp
    {
        internal static T Parse<T>(string jsonStr)
        {
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonStr)))
            {
                return (T)new DataContractJsonSerializer(typeof(T)).ReadObject(ms);
            }
        }
        internal static string strJson<T>(T jsonObj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                new DataContractJsonSerializer(jsonObj.GetType()).WriteObject(ms, jsonObj);
                return Encoding.UTF8.GetString(ms.ToArray());
            }
        }
    }
}

posted @ 2013-06-23 20:17  Danny Chen  阅读(509)  评论(0编辑  收藏  举报