32

怎么添加JArray进去JObjectjarrayObj更改into时出现异常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" 
}
4

4 回答 4

44

当您发布代码时,我发现您的代码存在两个问题。

  1. parameterNames需要是一个字符串数组,而不仅仅是一个带逗号的字符串。
  2. 您不能将 aJArray直接添加到 a JObject; 您必须将其放入 aJProperty并将其添加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"
}

此外,为了将来参考,如果您在代码中遇到异常,如果您在问题中准确说出异常是什么会很有帮助,这样我们就不必猜测了。它使我们更容易为您提供帮助。

于 2013-10-28T16:02:24.820 回答
10
// 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"
  ]
}
于 2019-12-20T21:24:34.487 回答
2

这很容易,

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.
于 2020-12-14T16:34:12.460 回答
2
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);
于 2019-05-30T12:30:44.583 回答