如何将JArray
添加到JObject
中? 将jarrayObj
更改为JObject
时出现异常。
parameterNames = "Test1,Test2,Test3";
JArray jarrayObj = new JArray();
foreach (string parameterName in parameterNames)
{
jarrayObj.Add(parameterName);
}
JObject ObjDelParams = new JObject();
ObjDelParams["_delete"] = jarrayObj;
JObject UpdateAccProfile = new JObject(
ObjDelParams,
new JProperty("birthday", txtBday),
new JProperty("email", txtemail))
我需要这种形式的输出:
{
"_delete": ["Test1","Test2","Test3"],
"birthday":"2011-05-06",
"email":"dude@test.com"
}
当您发布代码时,我看到您的代码存在两个问题。
-
parameterNames
需要是一个字符串数组,而不仅仅是一个带逗号的字符串。 - 你不能直接将
JArray
添加到JObject
;你必须把它放在一个JProperty
中,并将其添加到JObject
中,就像你对"生日"和"电子邮件"属性所做的那样。
更正的代码:
string[] parameterNames = new string[] { "Test1", "Test2", "Test3" };
JArray jarrayObj = new JArray();
foreach (string parameterName in parameterNames)
{
jarrayObj.Add(parameterName);
}
string txtBday = "2011-05-06";
string txtemail = "dude@test.com";
JObject UpdateAccProfile = new JObject(
new JProperty("_delete", jarrayObj),
new JProperty("birthday", txtBday),
new JProperty("email", txtemail));
Console.WriteLine(UpdateAccProfile.ToString());
输出:
{
"_delete": [
"Test1",
"Test2",
"Test3"
],
"birthday": "2011-05-06",
"email": "dude@test.com"
}
此外,为了将来参考,如果您在代码中遇到异常,如果您在问题中准确说明异常是什么,这样我们就不必猜测,这将很有帮助。 这使我们更容易为您提供帮助。
// array of animals
var animals = new[] { "cat", "dog", "monkey" };
// our profile object
var jProfile = new JObject
{
{ "birthday", "2011-05-06" },
{ "email", "dude@test.com" }
};
// Add the animals to the profile JObject
jProfile.Add("animals", JArray.FromObject(animals));
Console.Write(jProfile.ToString());
输出:
{
"birthday": "2011-05-06",
"email": "dude@test.com",
"animals": [
"cat",
"dog",
"monkey"
]
}
var jObject = new JObject();
jObject.Add("birthday", "2011-05-06");
jObject.Add("email", "dude@test.com");
var items = new [] { "Item1", "Item2", "Item3" };
var jSonArray = JsonConvert.SerializeObject(items);
var jArray = JArray.Parse(jSonArray);
jObject.Add("_delete", jArray);
这很容易,
JArray myarray = new JArray();
JObject myobj = new JObject();
// myobj.add(myarray); -> this is wrong. you can not add directly.
JProperty subdatalist = new JProperty("MySubData",myarray);
myobj.Add(subdata); // this is the correct way I suggest.