当前位置: 首页>>代码示例>>C#>>正文


C# JsonTextReader.Close方法代码示例

本文整理汇总了C#中Newtonsoft.Json.JsonTextReader.Close方法的典型用法代码示例。如果您正苦于以下问题:C# JsonTextReader.Close方法的具体用法?C# JsonTextReader.Close怎么用?C# JsonTextReader.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Newtonsoft.Json.JsonTextReader的用法示例。


在下文中一共展示了JsonTextReader.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: NewtonsoftDecode

 private static string NewtonsoftDecode(string input)
 {
     var sr = new StringReader(input);
     var reader = new JsonTextReader(sr);
     var output = reader.ReadAsString();
     reader.Close();
     return output;
 }
开发者ID:tmds,项目名称:Tmds.SockJS,代码行数:8,代码来源:JsonEncodingTest.cs

示例2: Load

        public static void Load(string path)
        {
            
            JsonTextReader reader = new JsonTextReader(new StreamReader(path));

            JsonSerializer serializer = new JsonSerializer();
            instance = serializer.Deserialize<BotConfig>(reader);
            reader.Close();
        }
开发者ID:stephenZh,项目名称:l2net,代码行数:9,代码来源:BotConfig.cs

示例3: ReadFile

        private static ModelList ReadFile()
        {
            var filePath = string.Format("c:\\models.json");

              var reader = new StreamReader(filePath);
              var jsonReader = new JsonTextReader(reader);
              var serializer = new JsonSerializer();
              var modelList = serializer.Deserialize<ModelList>(jsonReader);
              jsonReader.Close();

              return modelList;
        }
开发者ID:Code-Mayhem,项目名称:Chars-in-their-eyes,代码行数:12,代码来源:TextAnalyzerService.cs

示例4: InitializePopulation

        private static void InitializePopulation(string inputFile, string populationSize)
        {
            var jsSerializer = new JsonSerializer();
            var textReader = new StreamReader(inputFile);
            var reader = new JsonTextReader(textReader);
            var cfg = jsSerializer.Deserialize<Configuration>(reader);
            textReader.Close();
            reader.Close();

            Runner = new Runner(cfg, int.Parse(populationSize));

            Console.WriteLine("Initialized");
            Console.WriteLine("Best table score is: " + Runner.BestScore());
        }
开发者ID:andrewburgess,项目名称:SeatingChart,代码行数:14,代码来源:Program.cs

示例5: CloseInput

    public void CloseInput()
    {
      MemoryStream ms = new MemoryStream();
      JsonTextReader reader = new JsonTextReader(new StreamReader(ms));

      Assert.IsTrue(ms.CanRead);
      reader.Close();
      Assert.IsFalse(ms.CanRead);

      ms = new MemoryStream();
      reader = new JsonTextReader(new StreamReader(ms)) { CloseInput = false };

      Assert.IsTrue(ms.CanRead);
      reader.Close();
      Assert.IsTrue(ms.CanRead);
    }
开发者ID:handcraftsman,项目名称:Newtonsoft.Json,代码行数:16,代码来源:JsonTextReaderTest.cs

示例6: JsonInterpreter

        /// <summary>
        /// Initializes a new instance of the <see cref="JsonInterpreter"/> class.
        /// </summary>
        /// <param name="source">The <see cref="IResource"/>.</param>
        public JsonInterpreter(IResource source) : base(source)
        {
            string xmlContents = string.Empty;
            using(source)
            {
                JsonReader reader = new JsonTextReader(new StreamReader(source.Stream));
                reader.Read();

                XmlNodeConverter toXml = new XmlNodeConverter();
                XmlDocument xmlDoc = (XmlDocument)toXml.ReadJson(reader, typeof(XmlDocument));
                xmlContents = xmlDoc.OuterXml;
                reader.Close();                
            }

            IResource resource = new StaticContentResource(xmlContents);

            xmlInterpreter = new XmlConfigurationInterpreter(resource);
        }
开发者ID:techvenky,项目名称:mybatisnet,代码行数:22,代码来源:JsonInterpreter.cs

示例7: GetNextTopPosts

        public async Task GetNextTopPosts(Action<List<Post>> callback)
        {
            if (NextTopPosts == "/news3")
            {
                callback(new List<Post>());
                return;
            }

            HttpWebRequest request = HttpWebRequest.Create("http://" + serverAddress + NextTopPosts) as HttpWebRequest;
            request.Accept = "application/json";

            var response = await request.GetResponseAsync().ConfigureAwait(false);

            Stream stream = response.GetResponseStream();
            UTF8Encoding encoding = new UTF8Encoding();
            StreamReader sr = new StreamReader(stream, encoding);

            JsonTextReader tr = new JsonTextReader(sr);
            List<Post> data = new JsonSerializer().Deserialize<List<Post>>(tr);

            tr.Close();
            sr.Dispose();

            stream.Dispose();

            foreach (var item in data)
            {
                item.title = CleanTitleText(item.title);
                item.is_read = PostHistory.Contains(item.id);

                if (item.url.StartsWith("http") == false)
                    item.url = "http://news.ycombinator.com/item?id=" + item.id;
            }

            for (int i = 0; i < data.Count; i++)
            {
                data[i] = FormatPost(data[i]);
            }

            int index = NextTopPosts == "/news" ? 2 : Convert.ToInt32(NextTopPosts.Replace("/news", "")) + 1;
            NextTopPosts = "/news" + index;

            callback(data);
        }
开发者ID:cglong,项目名称:HackerNews,代码行数:44,代码来源:ServiceClient.cs

示例8: DeserializeObject

        /// <summary>
        /// Parse a string, and deserialize it into the supplied object.
        /// </summary>
        /// <param name="Object">The MudObject to write deserialized data to</param>
        /// <param name="Data"></param>
        internal static void DeserializeObject(MudObject Object, String Data)
        {
            var persistentProperties = new List<Tuple<System.Reflection.PropertyInfo, PersistAttribute>>(EnumeratePersistentProperties(Object));
            var jsonReader = new JsonTextReader(new System.IO.StringReader(Data));

            jsonReader.Read();
            jsonReader.Read();
            while (jsonReader.TokenType != JsonToken.EndObject)
            {
                var propertyName = jsonReader.Value.ToString();

                var prop = persistentProperties.FirstOrDefault(t => t.Item1.Name == propertyName);
                if (prop == null) throw new InvalidOperationException();
                jsonReader.Read();

                prop.Item1.SetValue(Object, prop.Item2.ReadValue(prop.Item1.PropertyType, jsonReader, Object), null);

            }

            jsonReader.Close();
        }
开发者ID:Reddit-Mud,项目名称:RMUD,代码行数:26,代码来源:ObjectSerialization.cs

示例9: GetDateJson

        public void GetDateJson(DateTime date, Action<ApiModel.Rootobject> success, Action<Exception> error)
        {
            string url = "http://www.someEventsWebsite.com"; // Obviously fake...

            Action<string> parseAndAddToDb = text =>
            {
                using (var stringReader = new StringReader(text))
                {
                    var converter = new JsonSerializer();
                    var jsonReader = new JsonTextReader(stringReader);
                    var rootobject = converter.Deserialize<ApiModel.Rootobject>(jsonReader);

                    _apiModelCacheService.AddDateModel(date, rootobject);

                    success(rootobject);

                    jsonReader.Close();
                }
            };

            _downloaderService.Download(url, parseAndAddToDb, error);
        }
开发者ID:CBurbidge,项目名称:BristolNightlife,代码行数:22,代码来源:WebApiModelService.cs

示例10: PopulateFormList

        /// <summary>
        /// Populates the recordset.
        /// </summary>
        public void PopulateFormList( )
        {
            try
            {
                string requesturl = _url;
                WebResponse webResponse = Utilities.DownloadRequest(requesturl, _username, _password);
                Encoding enc = Encoding.Default;
                string configuration = String.Empty;
                using (StreamReader reader = new StreamReader(webResponse.GetResponseStream()))
                {
                    configuration = reader.ReadToEnd();
                }
                Debug.WriteLine(configuration);

                Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();

                json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
                json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
                json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
                json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

                StringReader sr = new StringReader(configuration);
                Newtonsoft.Json.JsonTextReader jReader = new JsonTextReader(sr);
                Newtonsoft.Json.Linq.JArray result = (Newtonsoft.Json.Linq.JArray)json.Deserialize(jReader, Type.GetType("System.Data.DataSet"));

                //Get the Record Set
                jReader.Close();

                List<FormResult> results = new List<FormResult>();
                return;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
开发者ID:ZerionSoftware,项目名称:iFormEsriIntegration,代码行数:39,代码来源:FormAssignment.cs

示例11: GenerateClasses

        public void GenerateClasses(string nameSpace)
        {
            var numSamples = NumRowsToSample;

            _generatedClasses =
                GetInputFiles()
                    .Select(f =>
                    {
                        // TODO: Be a better error handler
                        try
                        {
                            var fs = new FileStream(f, FileMode.Open);
                            var sr = new StreamReader(fs);
                            var jtr = new JsonTextReader(sr);

                            var examples =
                                Enumerable
                                    .Range(0, numSamples)
                                    .Select(_ =>
                                    {
                                        while (jtr.Read())
                                            if (jtr.TokenType == JsonToken.StartObject)
                                                return JObject.Load(jtr).ToString();
                                        return null;
                                    })
                                    .Where(json => json != null);

                            var examplesJson = String.Format("[{0}]", String.Join(",\r\n", examples));

                            jtr.Close();
                            sr.Close();
                            fs.Close();

                            var className = Path.GetFileNameWithoutExtension(f).SanitiseClassName();
                            var finalNamespace = nameSpace + "." + className + "Input";
                            var outputStream = new MemoryStream();
                            var outputWriter = new StreamWriter(outputStream);

                            var jsg = new JsonClassGenerator
                            {
                                Example = examplesJson,
                                Namespace = finalNamespace,
                                MainClass = className,
                                OutputStream = outputWriter,
                                NoHelperClass = true,
                                UseProperties = true,
                                GeneratePartialClasses = true
                            };

                            jsg.GenerateClasses();

                            outputWriter.Flush();
                            outputStream.Seek(0, SeekOrigin.Begin);

                            var classDef = new StreamReader(outputStream)
                                .ReadToEnd()
                                .Replace("IList<", "List<");

                            classDef =
                                classDef.Substring(classDef.IndexOf(String.Format("namespace {0}", nameSpace),
                                    StringComparison.Ordinal));

                            NamespacesToAdd.Add(finalNamespace);

                            return new JsonFileGeneratedClass(this)
                            {
                                Namespace = finalNamespace,
                                ClassName = className,
                                DataFilePath = f,
                                ClassDefinition = classDef,
                                Success = true
                            };
                        }
                        catch (Exception e)
                        {
                            return new JsonFileGeneratedClass(this)
                            {
                                DataFilePath = f,
                                Success = false,
                                Error = e
                            };
                        }
                    })
                    .ToList();
        }
开发者ID:modulexcite,项目名称:jsondatacontext-linqpad,代码行数:85,代码来源:JsonFileInput.cs

示例12: Main

 public static void Main(string[] args)
 {
     WebClient client = new WebClient();
     foreach (string album in args)
     {
         Console.WriteLine("Retrieving album info..." /* from " + album + "..."*/);
         HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(album);
         HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
         Stream dataStream = resp.GetResponseStream();
         StreamReader reader = new StreamReader(dataStream);
         List<string> page = new List<string>();
         while (!reader.EndOfStream)
             page.Add(reader.ReadLine());
         reader.Close();
         dataStream.Close();
         resp.Close();
         int albumdatastart = page.IndexOf("var TralbumData = {");
         int albumdataend = page.IndexOf("};", albumdatastart);
         string jsondata = "{";
         for (int i = albumdatastart + 4; i < albumdataend; i++)
             jsondata += page[i];
         jsondata += " }";
         StringReader sr = new StringReader(jsondata);
         JsonTextReader jr = new JsonTextReader(sr);
         JsonSerializer js = new JsonSerializer();
         TralbumData data = js.Deserialize<TralbumData>(jr);
         jr.Close();
         sr.Close();
         string albumPath = data.current.title;
         foreach (char item in Path.GetInvalidPathChars())
             albumPath = albumPath.Replace(item, '_');
         albumPath = albumPath.Replace(": ", " - ");
         albumPath = Path.Combine(Environment.CurrentDirectory, albumPath);
         Directory.CreateDirectory(albumPath);
         Console.WriteLine("Found " + data.trackinfo.Length + " tracks in album \"" + data.current.title + "\"...");
         client.DownloadFile(data.artFullsizeUrl, Path.Combine(albumPath, "art.png"));
         string hostname = new Uri(album).Host;
         for (int i = 0; i < data.trackinfo.Length; i++)
         {
             Console.Write("Downloading track \"" + data.trackinfo[i].title + "\" (" + (i + 1) + "/" + data.trackinfo.Length + ")...");
             string filePath = data.trackinfo[i].title;
             if (data.trackinfo.Length < 100)
             {
                 filePath = (i + 1).ToString("D2") + " - " + filePath;
             }
             else
             {
                 filePath = (i + 1).ToString("D3") + " - " + filePath;
             }
             foreach (char item in Path.GetInvalidFileNameChars())
                 filePath = filePath.Replace(item, '_');
             filePath = filePath.Replace(": ", " - ").Replace('/', '-').Replace('\\', '-');
             filePath = Path.ChangeExtension(Path.Combine(albumPath, filePath), "mp3");
             client.DownloadFile(data.trackinfo[i].file["mp3-128"], filePath);
             IdSharp.Tagging.ID3v2.ID3v2Tag tag = new IdSharp.Tagging.ID3v2.ID3v2Tag(filePath);
             tag.Album = data.current.title;
             tag.AlbumArtist = tag.Artist = data.artist;
             IdSharp.Tagging.ID3v2.Frames.IAttachedPicture pic = tag.PictureList.AddNew();
             pic.Picture = System.Drawing.Image.FromFile(Path.Combine(albumPath, "art.png"));
             if (data.trackinfo[i].has_info != null)
             {
                 IdSharp.Tagging.ID3v2.Frames.IComments com = tag.CommentsList.AddNew();
                 com.Value = data.trackinfo[i].has_info;
             }
             tag.ReleaseTimestamp = data.current.release_date_datetime.ToString("s", System.Globalization.DateTimeFormatInfo.InvariantInfo);
             tag.Title = data.trackinfo[i].title;
             tag.TrackNumber = (i + 1).ToString(System.Globalization.NumberFormatInfo.InvariantInfo);
             tag.Year = data.current.release_date_datetime.Year.ToString("0000", System.Globalization.NumberFormatInfo.InvariantInfo);
             tag.CommercialInfoUrlList.AddNew().Value = album;
             tag.AudioFileUrl = "http://" + hostname + data.trackinfo[i].title_link;
             tag.ArtistUrlList.AddNew().Value = "http://" + hostname + "/";
             tag.Save(filePath);
             Console.WriteLine(" downloaded!");
         }
         File.WriteAllText(Path.Combine(albumPath, "Info.txt"), data.current.title + " by " + data.artist + "\r\nReleased " + data.current.release_date_datetime.ToString() + "\r\n" + data.current.about + "\r\n" + data.current.credits);
     }
 }
开发者ID:perXautomatik,项目名称:StormGET,代码行数:77,代码来源:Program.cs

示例13: Deserialize

        public static object Deserialize(string jsonText, Type valueType)
        {
            Newtonsoft.Json.JsonSerializer json = new Newtonsoft.Json.JsonSerializer();

            json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            json.ObjectCreationHandling = Newtonsoft.Json.ObjectCreationHandling.Replace;
            json.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
            json.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

            StringReader sr = new StringReader(jsonText);
            Newtonsoft.Json.JsonTextReader reader = new JsonTextReader(sr);
            object result = json.Deserialize(reader, valueType);
            reader.Close();

            return result;
        }
开发者ID:gitter-badger,项目名称:ApiFox,代码行数:16,代码来源:Helpers.cs

示例14: GetUserDataAsync

        public async Task<bool> GetUserDataAsync()
        {
            IsLoading = true;
            String strContent = await ViewModelLocator.Client.MakeOperationAsync(SupportedModules.USER,
                                                                              SupportedMethods.GetUserData);

            if (strContent != "")
            {
                User connectedUser = JsonConvert.DeserializeObject<User>(strContent);
                StringReader str = new StringReader(strContent);
                String institution = "";
                String platform = "";

                JsonTextReader reader = new JsonTextReader(str);
                while (reader.Read())
                {
                    if (reader.Value != null)
                    {
                        switch (reader.Value.ToString())
                        {
                            case "institutionName":
                                institution = reader.ReadAsString();
                                break;
                            case "platformName":
                                platform = reader.ReadAsString();
                                break;
                            default:
                                continue;
                        }
                    }
                }
                reader.Close();
                str.Close();

                Settings.UserSetting.setUser(connectedUser);
                Settings.InstituteSetting = institution;
                Settings.PlatformSetting = platform;

                IsLoading = false;
                return true;
            }
            IsLoading = false;
            return false;
        }
开发者ID:Okhoshi,项目名称:Claroline.WindowsPhone,代码行数:44,代码来源:ClarolineVM.cs

示例15: ReadText

 public void ReadText(string text)
 {
   JsonReader r = new JsonTextReader(new StringReader(text));
   r.Close();
 }
开发者ID:jonnyzzz,项目名称:NuGet.Demo,代码行数:5,代码来源:JSonService.cs


注:本文中的Newtonsoft.Json.JsonTextReader.Close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。