C#将类转换为JSON文件

zpgglvta  于 5个月前  发布在  C#
关注(0)|答案(2)|浏览(60)

我使用这个类:

class message
    {
        public content Content { get; set; }
        public from From { get; set;  }
        public personalizations Personalizations { get; set; }
    }

   
    public class content
    {
        public string type = "text/html";
        public string value = "html";
    }

    public class from
    {
        public string email = "[email protected]";
        public string name = "example";

    }
    public class personalizations
    {
        public List<to> tos { get; set; }
    }
    public class to
    {
        public string subject { get; set; }
        public string email { get; set; }
    }

字符串
我正在将类Message序列化为:

var msg = new message() { Content = new content() { type = "text/html", value = "html" },
        From = new from() { email = "[email protected]", name = "example" },
        Personalizations = new personalizations() { tos = new List<to>() { new to(), new to() } } };
    var data = JsonConvert.SerializeObject(msg);


我尝试获取每个父对象的数组。JSON输出格式为:

{
  "Content": {
   
     "type": "text/html",
    "value": "html"
  },
  "From": {
    "email": "[email protected]",
    "name": "example"
   },
  "Personalizations": 
   {
    "tos": [
      {
        "subject": null,
        "email": null
      },
      {
        "subject": null,
        "email": null
      }
    ]
  }
}


但我想要这种格式:

{
  "content": [
    {
      "type": "text/html", 
      "value": "Html"
    }
  ], 
  "from": {
    "email": "", 
    "name": ""
  }, 

  "personalizations": [
    {
      "subject": "",
      "to": [ { "email": "" }]
    },
    {
        "subject": "",
        "to": [{ "email": "" }]
    },
    {
        "subject": "",
        "to": [{ "email": "" }]
    }
    
    ]

}


我怎样才能把格式改成最后一个呢?
thanks in advance
编辑:
我想更改格式而不是值
举例说明:
在最后一个JSON示例中,我有一个个性化对象,它包含多个JSON对象,但在第一个示例中,我只有一个对象。

wpcxdonn

wpcxdonn1#

你可以把你想要的JSON复制到剪贴板上。然后你可以从编辑菜单中转到Visual Studio中的任何.cs文件,你可以展开“选择性粘贴”菜单。选择“粘贴JSON作为类”选项,你会得到这个:

public class Rootobject
{
    public Content[] content { get; set; }
    public From from { get; set; }
    public Personalization[] personalizations { get; set; }
}

public class From
{
    public string email { get; set; }
    public string name { get; set; }
}

public class Content
{
    public string type { get; set; }
    public string value { get; set; }
}

public class Personalization
{
    public string subject { get; set; }
    public To[] to { get; set; }
}

public class To
{
    public string email { get; set; }
}

字符串

wwtsj6pe

wwtsj6pe2#

根据你最近的评论,你想改变输出格式。你可以通过将属性“public string subject”从“to”类移动到“personalizations”类来实现,如下所示:
https://dotnetfiddle.net/40nBnl
顺便说一下,你应该看看C# naming conventions

相关问题