سؤال

if I try to call code below as it is, I receive

,"Name":"Newtonsoft.Json.Linq.JEnumerable`1[Newtonsoft.Json.Linq.JToken]"

as result. If I change the related line to

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

then I receive

Cannot access child value on Newtonsoft.Json.Linq.JProperty

any idea about what the problem might be and/or workaround? Thanks...

Stack Trace

  • at Newtonsoft.Json.Linq.JToken.get_Item(Object key)
  • at Newtonsoft.Json.Linq.Extensions.d__4`2.MoveNext()
  • at 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)

Code

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;
}
هل كانت مفيدة؟

المحلول

I'm making some assumptions about how your data is structured. Also, you really shouldn't build JSON manually, which you appear to be doing at the end there. Instead, I'm returning a KeyValuePair that can be added to a dictionary for serialization.

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]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top