如何将jarray对象添加到JObject [英] How to add jarray Object into JObject

查看:566
本文介绍了如何将jarray对象添加到JObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将JArray添加到JObject中?将jarrayObj更改为JObject时出现异常.

How to add JArray into JObject? I am getting an exception when changing the jarrayObj 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))

我需要以这种形式输出:

I need output in this form:

{
    "_delete": ["Test1","Test2","Test3"],
    "birthday":"2011-05-06",          
    "email":"dude@test.com" 
}

推荐答案

在您发布代码时,我看到了两个问题.

I see two problems with your code as you posted it.

  1. parameterNames必须是一个字符串数组,而不仅仅是一个带逗号的字符串.
  2. 不能将JArray直接添加到JObject;您必须将其放入JProperty并将那个添加到JObject中,就像使用生日"和电子邮件"属性一样.
  1. parameterNames needs to be an array of strings, not just a single string with commas.
  2. You can't add a JArray directly to a JObject; you have to put it in a JProperty and add that to the JObject, just like you are doing with the "birthday" and "email" properties.

更正的代码:

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

另外,如果您在代码中遇到异常,以供将来参考,如果在问题中确切说出异常是什么,这将很有帮助,这样我们就不必猜测.它使我们可以更轻松地为您提供帮助.

Also, for future reference, if you are getting an exception in your code, it is helpful if you say in your question exactly what the exception is, so that we don't have to guess. It makes it easier for us to help you.

这篇关于如何将jarray对象添加到JObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆