我正在尝试找到一种将数组添加到属性的方法。目前,我毫不费力地添加了非承包人。
var root = JObject.Parse(contractJson.ToString());
//get company name node
var companyNameMatches = root.Descendants()
.OfType<JObject>()
.Where(x => x["question"] != null && x["question"].ToString() == "Name of the company");
//add answer result to company name node
foreach (JObject jo in companyNameMatches)
{
jo.Add("answer", new JObject(new JProperty("result", Request.Form["Companyname"].ToString())));
}
因此,此行...如何使“答案”成为数组:
jo.Add("answer", new JObject(new JProperty("result", Request.Form["Companyname"].ToString())));
寻找此输出:
"answer":[
{
"result": "value"
}
]
答案 0 :(得分:3)
您需要将answer
属性设置为数组,因此应使用JArray
。更改此行:
jo.Add("answer", new JObject(new JProperty("result", Request.Form["Companyname"].ToString())));
收件人:
// Create the object to put in the array
var result = new JObject(new JProperty("result", Request.Form["Companyname"].ToString()));
// Create the array as the value for the answer property
jo.Add("answer", new JArray { result });
答案 1 :(得分:0)
这是因为您使用的是JObject
。
使用JArray
对象。 JArray
是JContainer
,它是一个JToken,您可以将其添加到JObject
中。
例如,用户的json:
string[] parameterNames = new string[] { "Test1", "Test2", "Test3" };
JArray jarrayObj = new JArray();
foreach (string parameterName in parameterNames)
{
jarrayObj.Add(parameterName);
}
string bDay = "2011-05-06";
string email = "dude@test.com";
JObject UpdateTestProfile = new JObject(
new JProperty("_delete", jarrayObj),
new JProperty("birthday", bDay),
new JProperty("email", email));
Console.WriteLine(UpdateTestProfile.ToString());