如何将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"
}
答案 0 :(得分:26)
我发布代码时会发现两个问题。
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"
}
此外,为了将来参考,如果您在代码中遇到异常,如果您在问题中准确说明异常是什么,那么我们就不必猜测了。这使我们更容易为您提供帮助。
答案 1 :(得分:1)
// 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"
]
}
答案 2 :(得分:0)
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);
答案 3 :(得分:0)
很简单,
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.