Как вы анализируете файл JSON с помощью JSON.net

Я пытаюсь прочитать файл JSON и проанализировать его. У меня есть этот код для чтения из моего файла

StreamReader re = new StreamReader("artists.json");
JsonTextReader reader = new JsonTextReader(re);

Но как мне теперь разобрать его из ридера, чтобы я мог искать данные в файле?

Я попытался прочитать документацию, но ничего не нашел


person user972616    schedule 04.03.2012    source источник


Ответы (3)


Если вы хотите загрузить его в тип JObject или динамический (а не десериализовать его в тип .NET), вы можете использовать JObject.Load

using(var sr = new StreamReader("artists.json")) 
{
    var reader = new JsonTextReader(sr);
    var jObject = JObject.Load(reader);

    //Get property from JObject
    var someValue = jObject.GetValue("someProperty").Value<string>();

    // JObject can be cast into a dynamic
    var dObject = (dynamic)jObject;
    someValue = (string)dObject.someProperty;

}
person andersh    schedule 28.03.2017

в ответ на «Некоторые подробности о том, как это реализовать, были бы полезны. – aknatn»

 using Newtonsoft.Json;
 using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Text;

 public class Program
  {
         public static void Main()
         {
           //JSON = {"Property1":"as","CollectionProperty":[{"prop1":"1","prop2":"2","prop3":"3"}]}

           //This Top part is just to build a stream 
           //- No need to do this if you are accessing a file 
           string JSON = "{\"Property1\":\"SomePropName\",\"CollectionProperty\":"+
           "[{\"prop1\":\"1\",\"prop2\":\"2\",\"prop3\":\"3\"}]}";
           byte[] byteArray = Encoding.UTF8.GetBytes(JSON);
           //byte[] byteArray = Encoding.ASCII.GetBytes(contents);
           MemoryStream stream = new MemoryStream(byteArray);
           // convert stream to string

           JsonSerializer se = new JsonSerializer();

           StreamReader re = new StreamReader(stream);
           JsonTextReader reader = new JsonTextReader(re);
           var DeserializedObject = se.Deserialize<Collections>(reader);

           Console.WriteLine(DeserializeObject.Property1);

           //"...so I can search data from the file?"
           //This is up to you and how you wanna handle it, but you now have JSON
           //Deserialized and stored in memory. 'How to search' depends on objects class
           //Also, Original question said he had the JSON. I would recommend using 
           //json2csharp.com/ or jsonutils.com/
           //to retrieve the classes in order to Deserialize it to your object. 

           //Note 1: You don't always have to cast it 
           //- I just always try to if and when I can
           //Note 2: Because you are using a StreamReader, 
           //this will account for Large JSON Objects 
         }


    public class Collections
    {
        public List<CollectionProperty> CollectionProperty = new List<CollectionProperty>();
        public string Property1;
    }

    public class CollectionProperty
    {
        public string prop1 { get; set; }
        public string prop2 { get; set; }
        public string prop3 { get; set; }
    }
  }
person Sam    schedule 16.08.2016
comment
Я сделаю это, и потоковый ридер не будет иметь для этого никакой ценности. Если я читаю его до конца, до строки, данные есть. Что я делаю неправильно? - person TheWizardOfTN; 26.04.2021

person    schedule
comment
Некоторые подробности о том, как реализовать это, были бы полезны. - person aknatn; 20.03.2015