无法访问JEnumerable <jtoken> children </jtoken>

时间:2014-05-14 14:33:56

标签: c# json linq json.net

如果我尝试按原样调用下面的代码,我会收到

,&#34;名称&#34;:&#34; Newtonsoft.Json.Linq.JEnumerable`1 [Newtonsoft.Json.Linq.JToken]&#34;

结果。如果我将相关行更改为

var property = myObject[propertyNames.Last()].FirstOrDefault();

然后我收到了

无法访问Newtonsoft.Json.Linq.JProperty上的子值

关于问题可能是什么和/或解决方法的任何想法?感谢...

堆栈跟踪

  • at Newtonsoft.Json.Linq.JToken.get_Item(Object key)
  • at Newtonsoft.Json.Linq.Extensions.d__4`2.MoveNext()
  • 在System.Linq.Enumerable.d__14`2.MoveNext()
  • at Newtonsoft.Json.Linq.Extensions.d__f`2.MoveNext()
  • at Newtonsoft.Json.Linq.Extensions.d__4`2.MoveNext()
  • at System.Linq.Enumerable.FirstOrDefault [TSource](IEnumerable`1 source)

代码

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

1 个答案:

答案 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]