我有这样的类:

class MyDate
{
    int year, month, day;
}

class Lad
{
    string firstName;
    string lastName;
    MyDate dateOfBirth;
}

我想把一个Lad对象变成一个JSON字符串,就像这样:

{
    "firstName":"Markoff",
    "lastName":"Chaney",
    "dateOfBirth":
    {
        "year":"1901",
        "month":"4",
        "day":"30"
    }
}

(没有格式)。我找到了这个链接,但是它使用的命名空间不在. net 4中。我还听说过JSON。NET,但是他们的网站似乎暂时宕机了,而且我不喜欢使用外部DLL文件。

除了手动创建JSON字符串写入器,还有其他选项吗?


当前回答

下面是另一个使用Cinchoo ETL的解决方案——一个开源库

public class MyDate
{
    public int year { get; set; }
    public int month { get; set; }
    public int day { get; set; }
}

public class Lad
{
    public string firstName { get; set; }
    public string lastName { get; set; }
    public MyDate dateOfBirth { get; set; }
}

static void ToJsonString()
{
    var obj = new Lad
    {
        firstName = "Tom",
        lastName = "Smith",
        dateOfBirth = new MyDate
        {
            year = 1901,
            month = 4,
            day = 30
        }
    };
    var json = ChoJSONWriter.Serialize<Lad>(obj);

    Console.WriteLine(json);
}

输出:

{
  "firstName": "Tom",
  "lastName": "Smith",
  "dateOfBirth": {
    "year": 1901,
    "month": 4,
    "day": 30
  }
}

声明:我是这个库的作者。

其他回答

使用Json。Net库,你可以从Nuget包管理器下载。

序列化为Json字符串:

 var obj = new Lad
        {
            firstName = "Markoff",
            lastName = "Chaney",
            dateOfBirth = new MyDate
            {
                year = 1901,
                month = 4,
                day = 30
            }
        };

var jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(obj);

反序列化到Object:

var obj = Newtonsoft.Json.JsonConvert.DeserializeObject<Lad>(jsonString );

序列化器

 public static void WriteToJsonFile<T>(string filePath, T objectToWrite, bool append = false) where T : new()
{
        var contentsToWriteToFile = JsonConvert.SerializeObject(objectToWrite, new JsonSerializerSettings
        {
            Formatting = Formatting.Indented,
        });
        using (var writer = new StreamWriter(filePath, append))
        {
            writer.Write(contentsToWriteToFile);
        }
}

对象

namespace MyConfig
{
    public class AppConfigurationSettings
    {
        public AppConfigurationSettings()
        {
            /* initialize the object if you want to output a new document
             * for use as a template or default settings possibly when 
             * an app is started.
             */
            if (AppSettings == null) { AppSettings=new AppSettings();}
        }

        public AppSettings AppSettings { get; set; }
    }

    public class AppSettings
    {
        public bool DebugMode { get; set; } = false;
    }
}

实现

var jsonObject = new AppConfigurationSettings();
WriteToJsonFile<AppConfigurationSettings>(file.FullName, jsonObject);

输出

{
  "AppSettings": {
    "DebugMode": false
  }
}

我会投票给ServiceStack的JSON Serializer:

using ServiceStack;

string jsonString = new { FirstName = "James" }.ToJson();

它也是。net中最快的JSON序列化器: http://www.servicestack.net/benchmarks/

另一个解决方案是使用内置的System.Text.Json(。NET Core 3.0+),其中对象是自给自足的,不公开所有可能的字段:

通过测试:

using NUnit.Framework;

namespace Intech.UnitTests
{
    public class UserTests
    {
        [Test]
        public void ConvertsItselfToJson()
        {
            var userName = "John";
            var user = new User(userName);

            var actual = user.ToJson();

            Assert.AreEqual($"{{\"Name\":\"{userName}\"}}", actual);
        }
    }
}

一个实现:

using System.Text.Json;
using System.Collections.Generic;

namespace Intech
{
    public class User
    {
        private readonly string name;

        public User(string name)
        {
            this.name = name;
        }

        public string ToJson()
        {
            var params = new Dictionary<string, string>{{"Name", name}};
            return JsonSerializer.Serialize(params);
        }
    }
}

你可以通过使用Newtonsoft.json来实现这一点。安装Newtonsoft。json从NuGet。然后:

using Newtonsoft.Json;

var jsonString = JsonConvert.SerializeObject(obj);