Newtonsoft 将对象序列化为自定义输出
Newtonsoft Serializing object to a custom output
我知道这是个愚蠢的问题,谁能帮我解决这个问题...?
在 C# 中需要低于输出,我正在使用 "www.newtonsoft.com" json 生成器 dll。
使用 JsonConvert.SerializeObject 所需的输出:
{
"must": [
{
"match": {
"pname": "TEXT_MATCH"
}
},
{
"_bool": {
"rname": "TEXT_BOOL"
}
}
]
}
我的 C# class 设计如下:
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"
}
}
]
}
在所需的输出中,数组中有 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"
}
}
]
}
我知道这是个愚蠢的问题,谁能帮我解决这个问题...?
在 C# 中需要低于输出,我正在使用 "www.newtonsoft.com" json 生成器 dll。
使用 JsonConvert.SerializeObject 所需的输出:
{
"must": [
{
"match": {
"pname": "TEXT_MATCH"
}
},
{
"_bool": {
"rname": "TEXT_BOOL"
}
}
]
}
我的 C# class 设计如下:
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"
}
}
]
}
在所需的输出中,数组中有 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"
}
}
]
}