Search code examples
c#c#-4.0elasticsearchjson.netnest-api

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.

Required output using JsonConvert.SerializeObject :

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

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

My C# class design is as below :

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 :

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

Solution

  • In the required output there are 2 objects in the array. In the one you get there is one object with both Match and Bool properties. 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"
          }
        }
      ]
    }