如果我尝试按原样调用下面的代码,我会收到
,"名称":" Newtonsoft.Json.Linq.JEnumerable`1 [Newtonsoft.Json.Linq.JToken]"
结果。如果我将相关行更改为
var property = myObject[propertyNames.Last()].FirstOrDefault();
然后我收到了
无法访问Newtonsoft.Json.Linq.JProperty上的子值
关于问题可能是什么和/或解决方法的任何想法?感谢...
void Main()
{
JObject objects = JObject.Parse("{\"Main\":[{\"Sub\":[{\"FieldName\":\"TEST\"}]}]}");
Console.WriteLine (SetProperty(objects, "Name", "Main", "Sub", "FieldName"));
}
private static string SetProperty(JObject objects, string propertyKey, params string[] propertyNames)
{
var myObject = objects.AsJEnumerable();
for (int counter = 0; counter < propertyNames.Count()-1; counter++)
{
myObject = myObject[propertyNames[counter]].Children();
}
var property = myObject[propertyNames.Last()];
string propertyValue = property == null
? string.Empty
: property.ToString();
string output = string.Format(",\"{0}\":\"{1}\"", propertyKey, propertyValue);
return output;
}
答案 0 :(得分:1)
我对数据的结构做了一些假设。此外,你真的不应该手动构建JSON,你似乎在那里做了。相反,我正在返回一个KeyValuePair
,可以添加到字典中进行序列化。
private static KeyValuePair<string, string> GetProperty(JObject objects,
string propertyKey, params string[] propertyNames)
{
JToken token = objects[propertyNames.First()];
foreach (var name in propertyNames.Skip(1))
token = token[0][name];
return new KeyValuePair<string, string>(propertyKey, (string)token);
}
// returns [Name, TEST]