简体   繁体   English

Newtonsoft将对象序列化为自定义输出

[英]Newtonsoft Serializing object to a custom output

I know this is silly question, can anyone help me out on this ...? 我知道这是一个愚蠢的问题,有人可以帮我解决这个问题吗?

Required below output in C#, am using "www.newtonsoft.com" json generator dll. 在C#的输出下面需要,正在使用“ www.newtonsoft.com” json生成器dll。

Required output using JsonConvert.SerializeObject : 使用JsonConvert.SerializeObject的必需输出:

{
  "must": [
    {
      "match": {
        "pname": "TEXT_MATCH"
      }
     },

     {
        "_bool": {
        "rname": "TEXT_BOOL"
      }
    }
  ]
}

My C# class design is as below : 我的C#类设计如下:

public class Rootobject
{
    public Must[] must { get; set; }
}

public class Must
{

    public Match match { get; set; }
    public Bool _bool { get; set; }
}

public class Match
{
    public string pname { get; set; }
}

public class Bool
{
    public string rname { get; set; }
}

Output I am getting after JsonConvert.SerializeObject is as below : 在JsonConvert.SerializeObject之后得到的输出如下:

{
  "must": [
    {
      "match": {
        "pname": "TEXT_MATCH"
      },
      "_bool": {
        "rname": "TEXT_BOOL"
      }
    }
  ]
}

In the required output there are 2 objects in the array. 在所需的输出中,数组中有2个对象。 In the one you get there is one object with both Match and Bool properties. 在第一个中,您将获得一个具有Match和Bool属性的对象。 The following way of creating the object and serializing should give what you're looking for: 以下创建对象和序列化的方法应该可以为您提供所需的东西:

static void Main(string[] args)
{
    Rootobject root = new Rootobject();
    root.must = new Must[2];
    root.must[0] = new Must() { match = new Match() { pname = "TEXT_MATCH" } };
    root.must[1] = new Must() { _bool = new Bool() { rname = "TEXT_BOOL" } };
    string result = Newtonsoft.Json.JsonConvert.SerializeObject(root, 
        Newtonsoft.Json.Formatting.Indented, 
        new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
    Console.WriteLine(result);
}

Output: 输出:

{
  "must": [
    {
      "match": {
        "pname": "TEXT_MATCH"
      }
    },
    {
      "_bool": {
        "rname": "TEXT_BOOL"
      }
    }
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM