不能't访问JEnumerable的孩子
本文关键字:JToken 孩子 JEnumerable 访问 不能 | 更新日期: 2023-09-27 18:03:15
如果我尝试调用下面的代码,我收到
,"名字":"Newtonsoft.Json.Linq.JEnumerable 1 [Newtonsoft.Json.Linq.JToken]"
作为结果。如果我将相关行改为
var property = myObject[propertyNames.Last()].FirstOrDefault();
那么我收到
无法访问Newtonsoft.Json.Linq.JProperty
知道问题可能是什么和/或解决方法吗?谢谢…
堆栈跟踪- 在Newtonsoft.Json.Linq.JToken
- 。get_Item(对象键)
- 2. Newtonsoft.Json.Linq.Extensions.d__4"movenext ()
- 2. System.Linq.Enumerable.d__14"movenext ()
- 2. Newtonsoft.Json.Linq.Extensions.d__f"movenext ()
- 2. Newtonsoft.Json.Linq.Extensions.d__4"movenext () 在System.Linq.Enumerable
- 。FirstOrDefault [TSource] (IEnumerable ' 1源)
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;
}
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;
}
我对数据的结构做了一些假设。此外,您确实不应该手动构建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]