csharp 将C#类对象写入/序列化为JSON对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 将C#类对象写入/序列化为JSON对象相关的知识,希望对你有一定的参考价值。


// Write/Serialize C# class object to JSON object
// API's used:

// 	* System.Runtime.Serialization - .NET 4.5 Serialization
// 	* JsonPrettyPrinterPlus


         private static void SaveMeasureResultsFile( Category3MeasureModel results, string measureBaseDirPath, DirectoryInfo measureDataDir, string measureDataDirSuffix)
        {
            var resultsSerializer = new DataContractJsonSerializer(typeof (Category3MeasureModel));
//            FileStream stream = File.OpenWrite((String.Format("{0}results.json", downloadDirectory)));
            var stream = new MemoryStream();
            resultsSerializer.WriteObject(stream, results);
            string resultString = Encoding.Default.GetString(stream.ToArray());

            stream.Close();
            stream.Dispose();
            var resultsFile = new StreamWriter(String .Format(" {0}results.json", measureDataDir.FullName));
            var beautifiedJson = BeautifyJson(resultString);
            resultsFile.Write(beautifiedJson);
            resultsFile.Flush();
            resultsFile.Close();
            AddFileToUnitTestProject(measureDataDirSuffix + @"results.json", measureBaseDirPath, measureDataDir.FullName);
        }



         private static string BeautifyJson( string json)
        {
            var jPrinter = new JsonPrettyPrinter(new JsonPPStrategyContext ());
            var output = jPrinter.PrettyPrint(json);
            return output;
        }


serialize array of objects:

        private static Person[] CreateMeasureModelFromJsonParams(string jsonParams)
        {
            var serializer = new DataContractJsonSerializer(typeof(Person[]));
            var stream = new MemoryStream(Encoding.UTF8.GetBytes(jsonParams));
            var measuresModel = serializer.ReadObject(stream);
            Console.WriteLine(measuresModel);
            stream.Close();
            return (Person[])measuresModel;
        }

    }

    [DataContract]
    class Person
    {
        [DataMember]
        public string FirstName { get; set; }
        [DataMember]
        public string LastName { get; set; }
    }



以上是关于csharp 将C#类对象写入/序列化为JSON对象的主要内容,如果未能解决你的问题,请参考以下文章

如何使用json.net自定义反序列化为对象

C# JSON 将文件反序列化为对象列表失败,并将字符串转换为集合错误

Restkit 0.24.0:如何将对象(包括对多关系)序列化为 JSON

如何在.Net Core 3.1中异步地将一个对象序列化为JSON并写入管道?

csharp RestSharp将JSON反序列化为动态

将JSON对象反序列化为嵌套的C#对象