【问题标题】:Newtonsoft Serializing object to a custom outputNewtonsoft 将对象序列化为自定义输出
【发布时间】:2015-10-29 09:26:11
【问题描述】:

我知道这是个愚蠢的问题,谁能帮我解决这个问题...?

在 C# 的输出下方需要,我正在使用“www.newtonsoft.com”json 生成器 dll。

使用 JsonConvert.SerializeObject 所需的输出:

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

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

我的 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; }
}

我在 JsonConvert.SerializeObject 之后得到的输出如下:

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

【问题讨论】:

  • 详细说明。您面临什么问题?
  • 我正在使用这个 json 文档作为对 elasticsearch 工具的查询,该工具接受 json 文档作为自身的输入。在这里,如果您看到“Must”类的所需输出是“match & bool”的容器,则这两个类都被一个额外的大括号(“{”)包围在其内部类周围。我无法使用 JsonConvert.SerializeObject 获得。有没有其他方法可以做到这一点?
  • 是的..我注意到了。不幸的是,我不这么认为。额外的花括号已从 Newtonsoft 中删除。

标签: c# c#-4.0 elasticsearch json.net nest-api


【解决方案1】:

在所需的输出中,数组中有 2 个对象。在你得到的那个中,有一个具有 Match 和 Bool 属性的对象。以下创建对象和序列化的方式应该可以满足您的需求:

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);
}

输出:

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

【讨论】:

    猜你喜欢
    • 2020-12-17
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多