c# - 如何从对象和变量创建 Json?

标签 c# json

我有一个包含以下变量的对象类:

class empleado
{
    public string nombre = "Nicolas";
    public string apellido = "Flores";
    public int edad= 22;
}

我可以用这行代码生成一个 Json:

string jsonResult = JsonConvert.SerializeObject(empleado);

但是我想在生成的 json 中添加除对象之外的其他数据,我该怎么做呢?

最佳答案

作为另一种方法,您可以像这样保留一个单独的模型。因此,您可以将您的 empleado 对象和您想要的其他属性分配给它,然后将其转换为 Json 对象。

class MyJsonObjectModel
{
    public string otherProperty1 = "My string 1";
    public string otherProperty2 = "My string 2";
    public int otherProperty3 = "1";

    public empleado empleadoModel;
}

string jsonResult = JsonConvert.SerializeObject(MyJsonObjectModel);

关于c# - 如何从对象和变量创建 Json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58810937/

相关文章:

c# - 为什么我的委托(delegate)在作为参数传递给方法时不起作用?

python - 如何使用 python 中的分页从 API 创建有效的 json 文件?

javascript - 将变量中的 JSON 传递给 HighCharts

c# - 原型(prototype)设计模式

c# - 将数据从 jQuery Ajax 发送到 MVC COntroller

json - MongoDB。如何更新数组内的json属性

jquery - 我无法使用 getJson 读取 JSON

ios - 如何在 NSMutableArray 中使用循环在任何索引处获取对象

c# - 在 xUnit.net 中等待测试设置代码中的任务?

c# - MVC 应用程序中的 SSRS 身份验证