首页 > 解决方案 > 将数组添加到属性

问题描述

我正在尝试找到一种将数组添加到属性的方法。目前,我正在毫无问题地添加非数组。

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

标签: c#asp.net-corejson.net

解决方案


你需要你的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 });

推荐阅读