Parse JSON String into List

后端 未结 5 2118
借酒劲吻你
借酒劲吻你 2021-02-14 11:55
string json = \"{\\\"People\\\":[{\\\"FirstName\\\":\\\"Hans\\\",\\\"LastName\\\":\\\"Olo\\\"}
                            {\\\"FirstName\\\":\\\"Jimmy\\\",\\\"LastName\         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-02-14 12:52

    I use this JSON Helper class in my projects. I found it on the net a year ago but lost the source URL. So I am pasting it directly from my project:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Runtime.Serialization.Json;
    using System.IO;
    using System.Text;
    /// 
    /// JSON Serialization and Deserialization Assistant Class
    /// 
    public class JsonHelper
    {
        /// 
        /// JSON Serialization
        /// 
        public static string JsonSerializer (T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }
        /// 
        /// JSON Deserialization
        /// 
        public static T JsonDeserialize (string jsonString)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }
    }
    

    You can use it like this: Create the classes as Craig W. suggested.

    And then deserialize like this

    RootObject root = JSONHelper.JsonDeserialize(json);
    

提交回复
热议问题