Json.net动态括号没有名称

时间:2017-01-03 20:35:58

标签: c# json dynamic json.net

您可以使用动态json创建括号,而不显示json字符串中出现的列表/数组的名称吗?否则我将需要重写整个部分。

问题是我还没弄明白如何在dymanic json中创建括号,而没有在它之前有一个名字。在我的json字符串中,值将包含一个包含所有条目的父括号,然后是一个包含时间戳的括号和另一个包装书籍的括号。 包含时间戳的括号&书籍不应该出现在他们面前。

使用此link,我非常接近我想要的格式,但我错过了时间和剩余条目的括号分隔。

示例代码:

JObject jsonobject = new JObject();
JObject jsonobject2 = new JObject();
dynamic topObject = jsonobject;
topObject.records = new JArray() as dynamic;
dynamic midObject = jsonobject2;
midObject.value = new JArray() as dynamic;
dynamic record = new JObject();
record.TIMESTAMP = DateTime.Now.ToString("MMMM dd yyyy HH:mm:ss");
record.ID = "sampleid";
midObject.value.Add(record);
//query for data
//loop through query
// add to record when data found ex:record.author=dr[0].ToString();
// midObject.value.Add(record);
// finished add data from query
topObject.records.Add(midObject);

string jsonstr = topObject.ToString();    

当前输出:

{
"records": [
{
"value": [
{
"TIMESTAMP": "January 03 2017 09:46:15",
"ID": "sampleID"
},
{
"Title": "Book2",
"Author": "author1"
},
{
"Title": "Book1"
"Author": "author1"
"Notes": "testtest"
}
]
}
]
}

期望的输出:

{
"records": [
{
"value": [
[ ------->bracket wrapping timestamp
{
"TIMESTAMP": "January 03 2017 09:46:15",
"ID": "sampleID"
}
] ------->bracket wrapping timestamp
,
[ ------->bracket wrapping books 
{
"Title": "Book2",
"Artist": "artist1"
},
{
"Title": "Book1"
"Artist": "artist1"
"Notes": "testtest"
}
] ------->bracket wrapping books 
] 
}
]
}

编辑:可能过于简单但书籍部分有20多个字段。每个json字符串只有一个时间戳,但每个请求可以有100到-1,000个书籍。

edit2:关于主要问题的标题/澄清。

1 个答案:

答案 0 :(得分:1)

据我所见,您只需要为所有记录添加另一个数组:

JObject jsonobject = new JObject();
JObject jsonobject2 = new JObject();
dynamic topObject = jsonobject;
topObject.records = new JArray() as dynamic;
dynamic midObject = jsonobject2;
midObject.value = new JArray() as dynamic;
dynamic arrayrecord = new JArray();
dynamic record = new JObject();
record.TIMESTAMP = DateTime.Now.ToString("MMMM dd yyyy HH:mm:ss");
record.ID = "sampleid";
arrayrecord.Add(record);
midObject.value.Add(arrayrecord);
//query for data
//loop through query
// add to record when data found ex:record.author=dr[0].ToString();
// midObject.value.Add(record);
// finished add data from query
topObject.records.Add(midObject);

string jsonstr = topObject.ToString();