문제

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