如何将jarray对象添加到JObject中

37
如何将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" 
}
4个回答

49

根据你发布的代码,我看到了两个问题。

  1. parameterNames 需要是一个字符串数组,而不仅仅是一个带有逗号的单个字符串。
  2. 你不能直接向 JObject 中添加一个 JArray;你必须将其放入一个 JProperty 中,并将其添加到 JObject 中,就像你对“birthday”和“email”属性所做的那样。

更正后的代码:

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"
}

同样,作为将来的参考,如果您在代码中遇到异常,如果您在问题中明确说明异常是什么,那么这将有助于我们解决问题,避免我们猜测。这可以让我们更容易地帮助您。


2
很棒的答案!此外,在原始代码中,foreach并不是必需的,因为JArray的构造函数接受对象数组作为参数。 - Do-do-new

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"
  ]
}

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);

3
如果您在回答中添加一些背景信息,将有助于读者理解。 - Milo
正是我所寻找的。 - K.S.

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.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接