LINQ и JSON.NET, когда имена свойства варьируются

parseInt () вынудит его быть целым числом типа или будет NaN (не число), если это не может выполнить преобразование.

var currentValue = parseInt($("#replies").text(),10);

второй параметр (основание) удостоверяется, что это анализируется как десятичное число.

9
задан Contango 19 April 2012 в 11:24
поделиться

2 ответа

Well it turned out the the best approach was to use a JsonTextReader and just rip through the data rather than trying to use LINQ. It's got lots on indentation which makes me unhappy but I suppose that's a direct effect of using a hierarchical data structure in the first place. Here's how to print the list of rows ("attributes") and their name/value collections:

        using (var file = File.OpenText(_fileWithGeom))
        {
            JsonReader reader = new JsonTextReader(file);

            while (reader.Read())
            {
                while (Convert.ToString(reader.Value) != "features")
                {
                    reader.Read();
                }

                Console.WriteLine("Found feature collections");

                // ignore stuff until we get to attribute array

                while (reader.Read())
                {
                    switch (Convert.ToString(reader.Value))
                    {
                        case "attributes":
                            Console.WriteLine("Found feature");
                            reader.Read(); // get pass attributes property

                            do
                            {
                                // As long as we're still in the attribute list...
                                if (reader.TokenType == JsonToken.PropertyName)
                                {
                                    var fieldName = Convert.ToString(reader.Value);
                                    reader.Read();
                                    Console.WriteLine("Name: {0}  Value: {1}", fieldName, reader.Value);
                                }

                                reader.Read();

                            } while (reader.TokenType != JsonToken.EndObject
                                     && Convert.ToString(reader.Value) != "attributes");
                            break;

                        case "geometry":
                            Console.WriteLine("Found geometry");
                            reader.Read();
                            break;
                    }
                }
            }
        }

And this time I'm also having to handle geometry, so check out this URL for the JSON that the above code is parsing:

http://sampleserver1.arcgisonline.com/ArcGIS/rest/services/WaterTemplate/WaterDistributionNetwork/MapServer/7/query?where=OBJECTID%3C10&returnGeometry=true&outSR=&outFields=*&f=pjson

3
ответ дан 4 December 2019 в 21:50
поделиться

Для быстрого и грязного (не -LINQ), чтобы получить атрибуты и значения, попробуйте следующее:

JObject jo = JObject.Parse(json);

foreach (JObject j in jo["features"])
{
  foreach (JProperty k in j["attributes"])
  {
    Console.WriteLine(k.Name + " = " + k.Value);
  }
}

Это не идеально, но он работает, когда вы не знаете имена полей, которые будут возвращаться. Если я найду способ лучше, я обновлю его.

6
ответ дан 4 December 2019 в 21:50
поделиться
Другие вопросы по тегам:

Похожие вопросы: