Represents a reader that provides fast, non-cached, forward-only access to JSON text data.
Наследование: JsonReader, IJsonLineInfo
Пример #1
0
        public void Load(ZipArchive iArchive)
        {
            JObject pJOtImages = null;
            ZipArchiveEntry pZAEImages = iArchive.GetEntry("images.json");
            if (pZAEImages != null)
            {
                using (Stream pStmImages = pZAEImages.Open())
                {
                    using (StreamReader pSRrReader = new StreamReader(pStmImages, Encoding.UTF8, false, 1024, true))
                    {
                        using (JsonTextReader pJTRReader = new JsonTextReader(pSRrReader))
                        {
                            pJOtImages = JObject.Load(pJTRReader);
                        }
                    }
                }
            }

            JArray pJAyImages = pJOtImages["images"].Value<JArray>(); ;
            foreach(JObject curImage in pJAyImages)
            {
                ProjectImage pPIeImage = ProjectImage.FromJSON(curImage);
                ZipArchiveEntry pZAEImage = iArchive.GetEntry(pPIeImage.ID);
                if (pZAEImage != null)
                {
                    using (Stream pStmImage = pZAEImage.Open())
                    {
                        pPIeImage.Image = Image.FromStream(pStmImage);
                        cDicImages.Add(pPIeImage.ID, pPIeImage);
                    }
                }
            }
        }
        public void ReadJsonWithInnerObjectTest()
        {
            const string json = "{\"properties\":{\"test1\":\"value1\",\"test2\": { \"innertest1\":\"innervalue1\" }}}";
            AttributesTableConverter target = new AttributesTableConverter();
            using (JsonTextReader reader = new JsonTextReader(new StringReader(json)))
            {
                JsonSerializer serializer = new JsonSerializer();

                // read start object token and prepare the next token
                reader.Read();
                reader.Read();
                AttributesTable result =
                    (AttributesTable)
                    target.ReadJson(reader, typeof(AttributesTable), new AttributesTable(), serializer);
                Assert.IsFalse(reader.Read()); // read the end of object and ensure there are no more tokens available
                Assert.IsNotNull(result);
                Assert.AreEqual(2, result.Count);
                Assert.AreEqual("value1", result["test1"]);
                Assert.IsNotNull(result["test2"]);
                Assert.IsInstanceOf<IAttributesTable>(result["test2"]);
                IAttributesTable inner = (IAttributesTable)result["test2"];
                Assert.AreEqual(1, inner.Count);
                Assert.AreEqual("innervalue1", inner["innertest1"]);
            }
        }
Пример #3
0
        /// <summary>
        /// Нажатие по кнопке "Открыть файл"
        /// </summary>
        private void OpenFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var serializer = new Newtonsoft.Json.JsonSerializer();

            serializer.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            serializer.TypeNameHandling  = Newtonsoft.Json.TypeNameHandling.Auto;
            serializer.Formatting        = Newtonsoft.Json.Formatting.Indented;

            var OpenFileDialog = new OpenFileDialog();

            if (OpenFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            var fileName = OpenFileDialog.FileName;

            using (StreamReader streamreader = new StreamReader(fileName))
            {
                using (Newtonsoft.Json.JsonReader jReader = new Newtonsoft.Json.JsonTextReader(streamreader))
                {
                    ListFigures.list = serializer.Deserialize <List <IFigure> >(jReader);

                    for (int i = 0; i < ListFigures.list.Count; i++)
                    {
                        var figure = ListFigures.list[i];
                        var row    = _table.NewRow();
                        row[0] = figure.Name;
                        row[1] = figure.X;
                        row[2] = figure.Y;
                        row[3] = figure.CalculationArea();
                        _table.Rows.Add(row);
                    }
                }
            }
        }
        protected override object DeserializeObject(ArraySegment <byte> value)
        {
            using (var ms = new MemoryStream(value.Array, value.Offset, value.Count, writable: false))
                using (var tr = new StreamReader(ms))
                    using (var jr = new Newtonsoft.Json.JsonTextReader(tr))
                    {
                        jr.Read();
                        if (jr.TokenType == JsonToken.StartArray)
                        {
                            // read type
                            var typeName = jr.ReadAsString();
                            var type     = readCache.GetOrAdd(typeName, x => Type.GetType(x, throwOnError: true)); // Get type or Register type

                            // read object
                            jr.Read();
                            var deserializedValue = jsonSerializer.Deserialize(jr, type);

                            return(deserializedValue);
                        }
                        else
                        {
                            throw new InvalidDataException("JsonTranscoder only supports [\"TypeName\", object]");
                        }
                    }
        }
    public void FloatParseHandling()
    {
      string json = "[1.0,1,9.9,1E-06]";

      JsonTextReader reader = new JsonTextReader(new StringReader(json));
      reader.FloatParseHandling = Json.FloatParseHandling.Decimal;

      Assert.IsTrue(reader.Read());
      Assert.AreEqual(JsonToken.StartArray, reader.TokenType);

      Assert.IsTrue(reader.Read());
      Assert.AreEqual(1.0m, reader.Value);
      Assert.AreEqual(typeof(decimal), reader.ValueType);
      Assert.AreEqual(JsonToken.Float, reader.TokenType);

      Assert.IsTrue(reader.Read());
      Assert.AreEqual(1L, reader.Value);
      Assert.AreEqual(typeof(long), reader.ValueType);
      Assert.AreEqual(JsonToken.Integer, reader.TokenType);

      Assert.IsTrue(reader.Read());
      Assert.AreEqual(9.9m, reader.Value);
      Assert.AreEqual(typeof(decimal), reader.ValueType);
      Assert.AreEqual(JsonToken.Float, reader.TokenType);

      Assert.IsTrue(reader.Read());
      Assert.AreEqual(Convert.ToDecimal(1E-06), reader.Value);
      Assert.AreEqual(typeof(decimal), reader.ValueType);
      Assert.AreEqual(JsonToken.Float, reader.TokenType);

      Assert.IsTrue(reader.Read());
      Assert.AreEqual(JsonToken.EndArray, reader.TokenType);
    }
Пример #6
0
        public void RunBenchmark(PocoSerializationFormat serializationFormat)
        {
            Newtonsoft.Json.JsonReader reader;
            switch (serializationFormat)
            {
            case PocoSerializationFormat.Text:
                reader = new CosmosDBToNewtonsoftReader(
                    Cosmos.Json.JsonReader.Create(
                        this.peoplePayload.Text));
                break;

            case PocoSerializationFormat.NewtonsoftText:
                if (!MemoryMarshal.TryGetArray(this.peoplePayload.Text, out ArraySegment <byte> segment))
                {
                    throw new InvalidOperationException("Failed to get segment");
                }

                reader = new Newtonsoft.Json.JsonTextReader(
                    new StreamReader(
                        new MemoryStream(segment.Array, index: segment.Offset, count: segment.Count)));
                break;

            case PocoSerializationFormat.Binary:
                reader = new CosmosDBToNewtonsoftReader(
                    Cosmos.Json.JsonReader.Create(
                        this.peoplePayload.Binary));
                break;

            default:
                throw new ArgumentOutOfRangeException(serializationFormat.ToString());
            }

            Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
            _ = serializer.Deserialize <List <Person> >(reader);
        }
Пример #7
0
        public void ConstructorTest()
        {
            string repositoryName = "Mvc3Application";
            string appName = "ConstructorTest";

            using (var repo = Git.CreateLocalRepository(repositoryName))
            {
                ApplicationManager.Run(appName, appManager =>
                {
                    using (HttpClient client = HttpClientHelper.CreateClient(appManager.ServiceUrl, appManager.DeploymentManager.Credentials))
                    {
                        HttpResponseMessage response = client.GetAsync("diagnostics/settings").Result.EnsureSuccessful();
                        using (var reader = new JsonTextReader(new StreamReader(response.Content.ReadAsStreamAsync().Result)))
                        {
                            JObject json = (JObject)JToken.ReadFrom(reader);
                            Assert.Equal(0, json.Count);
                        }
                    }

                    using (HttpClient client = HttpClientHelper.CreateClient(appManager.ServiceUrl, appManager.DeploymentManager.Credentials))
                    {
                        var ex = Assert.Throws<HttpRequestException>(() => client.GetAsync("diagnostics/settings/trace_level").Result.EnsureSuccessful());
                        Assert.Contains("404", ex.Message);
                    }
                });
            }
        }
Пример #8
0
        public static List<Redirect> ReadRedirects(HttpContext context)
        {
            if (RedirectHandler.Redirects == null)
            {
                string path = WebConfigurationManager.AppSettings["redirects"] ?? "~/App_Data/redirects.json";
                path = context.Server.MapPath(path);

                List<Redirect> newRedirects = new List<Redirect>();

                using (TextReader file = File.OpenText(path))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    string from = null;
                    while (reader.Read())
                    {
                        if (reader.TokenType == JsonToken.PropertyName)
                        {
                            from = ((string)reader.Value).ToLowerInvariant();
                        }
                        else if (reader.TokenType == JsonToken.String)
                        {
                            newRedirects.Add(new Redirect() { From = from, To = ((string)reader.Value).ToLowerInvariant() });
                        }
                    }
                }

                RedirectHandler.Redirects = newRedirects;
            }

            return RedirectHandler.Redirects;
        }
Пример #9
0
	protected override void HandleLoadedProperty (JsonTextReader reader, string propertyName, object readValue) {
		base.HandleLoadedProperty (reader, propertyName, readValue);
		switch(propertyName) {
			case "AimRotation": aimRotation = LoadManager.LoadQuaternion(reader); break;
			default: break;
		}
	}
    public void YahooFinance()
    {
      string input = @"{
""matches"" : [
{""t"":""C"", ""n"":""Citigroup Inc."", ""e"":""NYSE"", ""id"":""662713""}
,{""t"":""CHL"", ""n"":""China Mobile Ltd. (ADR)"", ""e"":""NYSE"", ""id"":""660998""}
,{""t"":""PTR"", ""n"":""PetroChina Company Limited (ADR)"", ""e"":""NYSE"", ""id"":""664536""}
,{""t"":""RIO"", ""n"":""Companhia Vale do Rio Doce (ADR)"", ""e"":""NYSE"", ""id"":""671472""}
,{""t"":""RIOPR"", ""n"":""Companhia Vale do Rio Doce (ADR)"", ""e"":""NYSE"", ""id"":""3512643""}
,{""t"":""CSCO"", ""n"":""Cisco Systems, Inc."", ""e"":""NASDAQ"", ""id"":""99624""}
,{""t"":""CVX"", ""n"":""Chevron Corporation"", ""e"":""NYSE"", ""id"":""667226""}
,{""t"":""TM"", ""n"":""Toyota Motor Corporation (ADR)"", ""e"":""NYSE"", ""id"":""655880""}
,{""t"":""JPM"", ""n"":""JPMorgan Chase \\x26 Co."", ""e"":""NYSE"", ""id"":""665639""}
,{""t"":""COP"", ""n"":""ConocoPhillips"", ""e"":""NYSE"", ""id"":""1691168""}
,{""t"":""LFC"", ""n"":""China Life Insurance Company Ltd. (ADR)"", ""e"":""NYSE"", ""id"":""688679""}
,{""t"":""NOK"", ""n"":""Nokia Corporation (ADR)"", ""e"":""NYSE"", ""id"":""657729""}
,{""t"":""KO"", ""n"":""The Coca-Cola Company"", ""e"":""NYSE"", ""id"":""6550""}
,{""t"":""VZ"", ""n"":""Verizon Communications Inc."", ""e"":""NYSE"", ""id"":""664887""}
,{""t"":""AMX"", ""n"":""America Movil S.A.B de C.V. (ADR)"", ""e"":""NYSE"", ""id"":""665834""}],
""all"" : false
}
";

      using (JsonReader jsonReader = new JsonTextReader(new StringReader(input)))
      {
        while (jsonReader.Read())
        {
          Console.WriteLine(jsonReader.Value);
        }
      }
    }
Пример #11
0
 public T Deserialize <T>(TextReader reader)
 {
     using (var jsonReader = new NewtonsoftJson.JsonTextReader(reader))
     {
         return(internalSerializer.Deserialize <T>(jsonReader));
     }
 }
Пример #12
0
 public object Deserialize(TextReader reader, Type objectType)
 {
     using (var jsonReader = new NewtonsoftJson.JsonTextReader(reader))
     {
         return(internalSerializer.Deserialize(jsonReader, objectType));
     }
 }
Пример #13
0
        protected virtual async System.Threading.Tasks.Task <ObjectResponseResult <T> > ReadObjectResponseAsync <T>(System.Net.Http.HttpResponseMessage response, System.Collections.Generic.IReadOnlyDictionary <string, System.Collections.Generic.IEnumerable <string> > headers)

        {
            if (response == null || response.Content == null)
            {
                return(new ObjectResponseResult <T>(default(T), string.Empty));
            }

            try
            {
                using (var responseStream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))

                    using (var streamReader = new System.IO.StreamReader(responseStream))

                        using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader))

                        {
                            var serializer = Newtonsoft.Json.JsonSerializer.Create(_settings.Value);

                            var typedBody = serializer.Deserialize <T>(jsonTextReader);

                            return(new ObjectResponseResult <T>(typedBody, string.Empty));
                        }
            }

            catch (JsonException exception)

            {
                var message = "Could not deserialize the response body stream as " + typeof(T).FullName + ".";

                throw new ApiException(message, (int)response.StatusCode, string.Empty, headers, exception);
            }
        }
Пример #14
0
 public static Quaternion LoadQuaternion(JsonTextReader reader)
 {
     Quaternion rotation = new Quaternion(0, 0, 0, 0);
     if (reader == null) return rotation;
     string currVal = "";
     while (reader.Read())
     {
         if (reader.Value != null)
         {
             if (reader.TokenType == JsonToken.PropertyName) currVal = (string)reader.Value;
             else
             {
                 switch (currVal)
                 {
                     case "x": rotation.x = (float)(double)reader.Value; break;
                     case "y": rotation.y = (float)(double)reader.Value; break;
                     case "z": rotation.z = (float)(double)reader.Value; break;
                     case "w": rotation.w = (float)(double)reader.Value; break;
                     default: break;
                 }
             }
         }
         else if (reader.TokenType == JsonToken.EndObject) return rotation;
     }
     return rotation;
 }
        public RequestForm makeRequestForm(JObject json)
        {
            string currManagerName = (string)json["current"]["bazookaInfo"]["managerId"];
            string futureManagerName = (string)json["future"]["bazookaInfo"]["managerId"];
            int managerID = GetIDFromName(currManagerName);
            int f_managerID = GetIDFromName(futureManagerName);
            json["current"]["bazookaInfo"]["managerId"] = managerID;
            json["current"]["ultiproInfo"]["supervisor"] = managerID;
            json["future"]["bazookaInfo"]["managerId"] = f_managerID;
            json["future"]["ultiproInfo"]["supervisor"] = f_managerID;

            UserController uc = new UserController();
            string[] name = uc.GetUserName().Split('.');
            string creatorName = name[0] + " " + name[1];
            int creatorID = GetIDFromName(creatorName);

            RequestForm obj = null;
            using (var sr = new StringReader(json.ToString()))
            using (var jr = new JsonTextReader(sr))
            {
                var js = new JsonSerializer();
                obj = (RequestForm)js.Deserialize<RequestForm>(jr);
            }
            obj.EmployeeId = GetIDFromName((string)json["name"]);
            obj.CreatedByID = creatorID;
            obj.Current.BazookaInfo.SecurityItemRights = "";
            obj.ReviewInfo.FilesToBeRemovedFrom = "(" + obj.Current.BazookaInfo.Group + ")" + currManagerName.Replace(" ", ".")+" "+obj.ReviewInfo.FilesToBeRemovedFrom;
            obj.ReviewInfo.FilesToBeAddedTo = "(" + obj.Future.BazookaInfo.Group + ")" + futureManagerName.Replace(" ", ".")+" "+obj.ReviewInfo.FilesToBeAddedTo;

            return obj;
        }
        private void LoadJsonFilesIfNeeded()
        {
            if (_environmentDeployInfosByName != null)
              {
            return;
              }

              _environmentDeployInfosByName = new Dictionary<string, EnvironmentDeployInfo>();

              var jsonSerializer = new JsonSerializer();

              foreach (string jsonFilePath in Directory.GetFiles(_configurationFilesDirPath, "*.json", SearchOption.TopDirectoryOnly))
              {
            EnvironmentDeployInfoJson environmentDeployInfoJson = null;

            using (FileStream fileStream = File.OpenRead(jsonFilePath))
            using(var streamReader = new StreamReader(fileStream))
            using (var jsonReader = new JsonTextReader(streamReader))
            {
              environmentDeployInfoJson = jsonSerializer.Deserialize<EnvironmentDeployInfoJson>(jsonReader);
            }

            if (environmentDeployInfoJson != null)
            {
              EnvironmentDeployInfo environmentDeployInfo = ConvertToDomain(environmentDeployInfoJson);

              _environmentDeployInfosByName.Add(environmentDeployInfo.TargetEnvironment, environmentDeployInfo);
            }
              }
        }
Пример #17
0
 public static RuntimeGraph ReadRuntimeGraph(TextReader textReader)
 {
     using (var jsonReader = new JsonTextReader(textReader))
     {
         return ReadRuntimeGraph(JToken.Load(jsonReader));
     }
 }
        public IStorageProviderConfig GetConfig(string name) {
            if (String.IsNullOrWhiteSpace(name)) throw new ArgumentNullException(nameof(name));

            using (var configStream = fs.File.OpenRead(this.configFilePath)) {
                using (var streamReader = new StreamReader(configStream)) {
                    using (var jsonReader = new JsonTextReader(streamReader)) {

                        var config = JToken.Load(jsonReader, new JsonLoadSettings {
                            CommentHandling = CommentHandling.Ignore,
                            LineInfoHandling = LineInfoHandling.Ignore
                        });

                        var namedConfig = config[name];
                        if (namedConfig == null) {
                            return null;
                        }

                        string type = namedConfig.Value<string>(TypeKey);

                        if (String.IsNullOrWhiteSpace(type)) {
                            return null;
                        }

                        var converter = converterFactory.GetConverter(type);
                        var providerConfig = converter.ToConfig(namedConfig[ConfigKey]);

                        return providerConfig;
                    }
                }
            }
        }
Пример #19
0
        /// <summary>
        /// Parses the json string and returns a Dictionary of verification pairs
        /// </summary>
        /// <param name="verificationFormatJSON"></param>
        /// <returns></returns>
        public static Dictionary<string, object> BuildVerifyDictionary(string verificationFormatJSON)
        {
            bool isStringValid = ValidateJsonString(verificationFormatJSON);

            // Immediately fail if the string format is not valid
            Validity.Assert(isStringValid);

            Dictionary<string, object> verification = new Dictionary<string, object>();
            JsonTextReader reader = new JsonTextReader(new StringReader(verificationFormatJSON));
            while (reader.Read())
            {
                // Start of new item
                if (reader.TokenType == JsonToken.StartObject)
                {
                    // Start of new entry
                    // Ignore and move to the entry pair
                }
                else if (reader.TokenType == JsonToken.PropertyName)
                {
                    KeyValuePair<string, object> pair = GetVerifyPair(reader);
                    if (verification.ContainsKey(pair.Key))
                    {
                        verification[pair.Key] = pair.Value;
                    }
                    else
                    {
                        verification.Add(pair.Key, pair.Value);
                    }
                }
            }
            return verification;
        }
 public object Deserialize(Stream body, Type messageType)
 {
     var streamReader = new StreamReader(body);
     var reader = new JsonTextReader(streamReader);
     var serializer = new JsonSerializer();
     return serializer.Deserialize(reader, messageType);
 }
Пример #21
0
        private void ParseCoordinate(JsonTextReader reader)
        {
            if (!reader.Read() || reader.TokenType != JsonToken.StartObject)
                throw new InvalidOperationException();

            var allCoord = new List<Tuple<int, System.Drawing.PointF[]>>();
            while (reader.Read() && reader.TokenType != JsonToken.EndObject) {
                if (reader.TokenType != JsonToken.PropertyName) throw new InvalidOperationException();

                var key = Convert.ToInt32(reader.Value);

                if (!reader.Read() || reader.TokenType != JsonToken.StartArray) throw new InvalidOperationException();

                var coordinates = new List<System.Drawing.PointF>();
                while (reader.Read() && reader.TokenType != JsonToken.EndArray) {
                    if (reader.TokenType != JsonToken.StartArray) throw new InvalidOperationException();

                    if (!reader.Read() || reader.TokenType != JsonToken.String) throw new InvalidOperationException();
                    var x = float.Parse((string)reader.Value);

                    if (!reader.Read() || reader.TokenType != JsonToken.String) throw new InvalidOperationException();
                    var y = float.Parse((string)reader.Value);

                    if (!reader.Read() || reader.TokenType != JsonToken.EndArray) throw new InvalidOperationException();

                    coordinates.Add(new System.Drawing.PointF(x, y));
                }

                allCoord.Add(Tuple.Create(key, coordinates.ToArray()));
            }

            _Coordinates = allCoord.ToArray();
        }
        public static DateTimeOffset? ParseDateTimeOffset(JToken value)
        {
            var jValue = value as JValue;
            if (jValue != null)
            {
                if (jValue.Value == null)
                    return null;

                if (jValue.Value is DateTimeOffset)
                    return jValue.Value<DateTimeOffset>();
            }

            var rawValue = value.AsString();

            if (string.IsNullOrWhiteSpace(rawValue))
                return null;

            rawValue = rawValue.Replace("NeoDate", "Date");

            if (!DateRegex.IsMatch(rawValue))
            {
                DateTimeOffset parsed;
                if (!DateTimeOffset.TryParse(rawValue, out parsed))
                    return null;
            }

            var text = string.Format("{{\"a\":\"{0}\"}}", rawValue);
            var reader = new JsonTextReader(new StringReader(text)) {DateParseHandling = DateParseHandling.DateTimeOffset};
            reader.Read(); // JsonToken.StartObject
            reader.Read(); // JsonToken.PropertyName
            return reader.ReadAsDateTimeOffset();
        }
Пример #23
0
 public void Deserialize(Stream stream)
 {
     Debug.Assert(_serializer != null);
     Debug.Assert(stream != null);
     JsonReader reader = new JsonTextReader(new StreamReader(stream));
     _serializer.Deserialize(reader);
 }
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, System.Net.Http.HttpContent content, IFormatterLogger formatterLogger)
        {
            var task = Task<object>.Factory.StartNew(() =>
            {
                var ser = JsonNetExtensions.GetJsonSerializer();

                using (var sr = new StreamReader(readStream))
                {
                    using (var jreader = new JsonTextReader(sr))
                    {
                        ser.Converters.Add(new IsoDateTimeConverter());
                        return ser.Deserialize(jreader, type);
                    }
                }
                /*
                var sr = new StreamReader(stream);
                var jreader = new JsonTextReader(sr);

                var ser = new JsonSerializer();
                ser.Converters.Add(new IsoDateTimeConverter());

                object val = ser.Deserialize(jreader, type);
                return val;*/
            });

            return task;
        }
Пример #25
0
 public virtual T ReadJSONResponse <T>(HttpWebResponse resp)
 {
     using (var rs = Duplicati.Library.Utility.AsyncHttpRequest.TrySetTimeout(resp.GetResponseStream()))
         using (var tr = new System.IO.StreamReader(rs))
             using (var jr = new Newtonsoft.Json.JsonTextReader(tr))
                 return(new Newtonsoft.Json.JsonSerializer().Deserialize <T>(jr));
 }
Пример #26
0
        private void openFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var serializer = new Newtonsoft.Json.JsonSerializer();

            serializer.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            serializer.TypeNameHandling  = Newtonsoft.Json.TypeNameHandling.Auto;
            serializer.Formatting        = Newtonsoft.Json.Formatting.Indented;

            var OpenFileDialog = new OpenFileDialog();

            if (OpenFileDialog.ShowDialog() == DialogResult.Cancel)
            {
                return;
            }
            var fileName = OpenFileDialog.FileName;

            using (StreamReader streamreader = new StreamReader(fileName))
            {
                using (Newtonsoft.Json.JsonReader jReader = new Newtonsoft.Json.JsonTextReader(streamreader))
                {
                    ListCatalog.list = serializer.Deserialize <List <ICatalogue> >(jReader);

                    for (int i = 0; i < ListCatalog.list.Count; i++)
                    {
                        var catalog = ListCatalog.list[i];
                        var row     = _datatable.NewRow();
                        row[0] = catalog.Name;
                        row[1] = catalog.YearPublishing;
                        row[2] = catalog.GetDescription();
                        _datatable.Rows.Add(row);
                    }
                }
            }
        }
Пример #27
0
        /// <summary>
        /// Parses the text representing a JSON object
        /// into an instance of the type specified.
        /// </summary>
        public static object FromJson(this Stream stream, Type entityType, JsonNet.JsonSerializerSettings settings)
        {
            _ = stream ?? throw new ArgumentNullException(nameof(stream));

            if (!stream.CanRead)
            {
                throw new NotSupportedException($"{nameof(stream)} is not readable.");
            }
            if (stream.CanSeek)
            {
                stream.Position = 0;
            }

            try
            {
                var serializer = JsonNet.JsonSerializer.Create(settings);
                using var streamReader = new StreamReader(stream, leaveOpen: true);
                using var jsonReader   = new JsonNet.JsonTextReader(streamReader);
                return(serializer.Deserialize(jsonReader, entityType));
            }
            catch
            {
                return(null);
            }
            finally
            {
                if (stream.CanSeek)
                {
                    stream.Position = 0;
                }
            }
        }
Пример #28
0
        public static void Load()
        {
            players.Clear();

            string filename = "SavedGames" + Path.DirectorySeparatorChar + "Players.json";
            if (File.Exists(filename))
            {
                //read contents of file
                string input;
                using (StreamReader sr = new StreamReader(filename))
                {
                    input = sr.ReadToEnd();
                }
                if (input != null)
                {
                    //parse contents of file
                    using (JsonTextReader reader = new JsonTextReader(new StringReader(input)))
                    {
                        while (reader.Read())
                        {
                            if (reader.Value != null)
                            {
                                if (reader.TokenType == JsonToken.PropertyName)
                                {
                                    if ((string)reader.Value == "Players") LoadPlayers(reader);
                                }
                            }
                        }
                    }
                }
            }
        }
Пример #29
0
        /// <summary>
        /// 指定の物を追加する
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async Task <PersonView> Post(PersonView person)
        {
            //最新IDにする
            person.id = maxId();

            var js = new Newtonsoft.Json.JsonSerializer();
            var sw = new System.IO.StringWriter();

            js.Serialize(sw, person);
            var hc = new HttpClient();

            hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var json = sw.ToString();
            var cont = new StringContent(json, Encoding.UTF8, "application/json");
            var res  = await hc.PostAsync(common.GetURL() + "people", cont);

            var str = await res.Content.ReadAsStringAsync();

            testMess.Text = str;

            var jr   = new Newtonsoft.Json.JsonTextReader(new System.IO.StringReader(str));
            var item = js.Deserialize <PersonView>(jr);

            return(item);
        }
Пример #30
0
        static void Main(string[] args)
        {
            var reader = new StreamReader("testfile.json");

            reader.ReadLine();
            JsonTextReader rd     = new Newtonsoft.Json.JsonTextReader(reader);
            var            stream = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(stream);

            while (rd.Read())
            {
                Console.WriteLine(rd.TokenType + "\t" + rd.Value);
                if (rd.TokenType == JsonToken.PropertyName)
                {
                    var value = rd.Value.ToString();
                    if (value == "Chunks" || value == "SoundIntervals")
                    {
                        rd.Skip();
                        continue;
                    }
                }
                writer.WriteToken(rd, false);
            }
            writer.Close();
            Console.WriteLine(stream.GetStringBuilder().ToString());
        }
        public void Parse()
        {
            if (_IsParsed) return;

            var json = Encoding.UTF8.GetString(this.data);
            using (var strReader = new System.IO.StringReader(json)) {
                using (var r = new JsonTextReader(strReader)) {
                    while (r.Read()) {
                        if (r.TokenType == JsonToken.PropertyName) {
                            switch (r.Value.ToString()) {
                                case "region":
                                    ParseRegions(r);
                                    break;
                                case "nonpop":
                                    _NonPops = r.ReadInt32Array();
                                    break;
                                case "item":
                                    _Items = r.ReadInt32Array();
                                    break;
                                case "instance_contents":
                                    _InstanceContents = r.ReadInt32Array();
                                    break;
                                default:
                                    Console.Error.WriteLine("Unknown 'BNpcName' data key: {0}", r.Value);
                                    throw new NotSupportedException();
                            }
                        }
                    }
                }
            }

            _IsParsed = true;
        }
Пример #32
0
        public void Parse()
        {
            if (_IsParsed)
                return;

            var json = Encoding.UTF8.GetString(this.data);
            using (var strReader = new System.IO.StringReader(json)) {
                using (var r = new JsonTextReader(strReader)) {
                    while (r.Read()) {
                        if (r.TokenType == JsonToken.PropertyName) {
                            switch (r.Value.ToString()) {
                                case "client_quest":
                                    _AsQuestClient = r.ReadInt32Array();
                                    break;
                                case "coordinate":
                                    ParseCoordinate(r);
                                    break;
                                case "quest":
                                    _Quests = r.ReadInt32Array();
                                    break;
                                case "shop":
                                    ParseShops(r);
                                    break;
                                default:
                                    Console.Error.WriteLine("Unknown 'ENpcResident' data key: {0}", r.Value);
                                    throw new NotSupportedException();
                            }
                        }
                    }
                }
            }

            _IsParsed = true;
        }
Пример #33
0
        //public JsonFormatter()
        //{
        //  SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/json"));
        //  SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
        //}
        public override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var task = new TaskCompletionSource<object>();

              using (var ms = new MemoryStream())
              {
            readStream.CopyTo(ms);
            //ms.Seek(0, SeekOrigin.Begin);

            //var result = JsonSchemaValidator.Instance().Validate(ms, type);

            //if (!string.IsNullOrWhiteSpace(result))
            //  task.SetResult(result);
            //else
            {
              ms.Seek(0, SeekOrigin.Begin);
              using (var reader = new JsonTextReader(new StreamReader(ms)))
              {
            var serializer = new JsonSerializer();
            task.SetResult(serializer.Deserialize(reader, type));
              }
            }
              }
              return task.Task;
        }
Пример #34
0
 public T ReadJSONResponse <T>(HttpWebResponse resp)
 {
     using (var rs = resp.GetResponseStream())
         using (var tr = new System.IO.StreamReader(rs))
             using (var jr = new Newtonsoft.Json.JsonTextReader(tr))
                 return(new Newtonsoft.Json.JsonSerializer().Deserialize <T>(jr));
 }
Пример #35
0
        public void ReadBigInteger()
        {
            string json = @"{
    ParentId: 1,
    ChildId: 333333333333333333333333333333333333333,
}";

            JsonTextReader jsonTextReader = new JsonTextReader(new StringReader(json));

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.StartObject, jsonTextReader.TokenType);

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.PropertyName, jsonTextReader.TokenType);

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.Integer, jsonTextReader.TokenType);

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.PropertyName, jsonTextReader.TokenType);

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.Integer, jsonTextReader.TokenType);
            Assert.AreEqual(typeof(BigInteger), jsonTextReader.ValueType);
            Assert.AreEqual(BigInteger.Parse("333333333333333333333333333333333333333"), jsonTextReader.Value);

            Assert.IsTrue(jsonTextReader.Read());
            Assert.AreEqual(JsonToken.EndObject, jsonTextReader.TokenType);

            Assert.IsFalse(jsonTextReader.Read());

            JObject o = JObject.Parse(json);
            var i = (BigInteger)((JValue)o["ChildId"]).Value;
            Assert.AreEqual(BigInteger.Parse("333333333333333333333333333333333333333"), i);
        }
        ConsumeContext IMessageDeserializer.Deserialize(ReceiveContext receiveContext)
        {
            try
            {
                var messageEncoding = GetMessageEncoding(receiveContext);

                MessageEnvelope envelope;
                using (var body = receiveContext.GetBody())
                using (var reader = new StreamReader(body, messageEncoding, false, 1024, true))
                using (var jsonReader = new JsonTextReader(reader))
                {
                    envelope = _deserializer.Deserialize<MessageEnvelope>(jsonReader);
                }

                return new JsonConsumeContext(_deserializer, _objectTypeDeserializer, _sendEndpointProvider, _publishEndpointProvider, receiveContext, envelope);
            }
            catch (JsonSerializationException ex)
            {
                throw new SerializationException("A JSON serialization exception occurred while deserializing the message envelope", ex);
            }
            catch (SerializationException)
            {
                throw;
            }
            catch (Exception ex)
            {
                throw new SerializationException("An exception occurred while deserializing the message envelope", ex);
            }
        }
        public IEnumerable <Document> GetResponseDocuments()
        {
            if (Enabled == false)
            {
                return(Array.Empty <Document>());
            }

            var             files     = Directory.GetFiles(BaseCachePath, "*.meta");
            List <Document> documents = new List <Document>(files.Length * 2);

            foreach (var path in files)
            {
                bool encrypted = path.EndsWith(".e.meta");

                //deserialize the document meta data
                using (var fs = File.OpenRead(path))
                    using (StreamReader reader = encrypted ? new StreamReader(CreateDecryptionStream(fs)) : new StreamReader(fs))
                        using (var json = new Newtonsoft.Json.JsonTextReader(reader))
                        {
                            var serializer = new Newtonsoft.Json.JsonSerializer();
                            serializer.Converters.Add(new DocumentCreationConverter());

                            var doc = serializer.Deserialize <Document>(json);
                            documents.Add(doc);
                        }
            }

            return(documents);
        }
Пример #38
0
 public static StreamMetadata FromJsonBytes(byte[] json)
 {
     using (var reader = new JsonTextReader(new StreamReader(new MemoryStream(json))))
     {
         return FromJsonReader(reader);
     }
 }
Пример #39
0
 public static void LoadGame(string filename)
 {
     char separator = Path.DirectorySeparatorChar;
     string path = "SavedGames" + separator + PlayerManager.GetPlayerName() + separator + filename + ".json";
     if(!File.Exists(path)) {
         Debug.Log("Unable to find " + path + ". Loading will crash, so aborting.");
         return;
     }
     string input;
     using(StreamReader sr = new StreamReader(path)) {
         input = sr.ReadToEnd();
     }
     if(input != null) {
         //parse contents of file
         using(JsonTextReader reader = new JsonTextReader(new StringReader(input))) {
             while(reader.Read()) {
                 if(reader.Value!=null) {
                     if(reader.TokenType == JsonToken.PropertyName) {
                         string property = (string)reader.Value;
                         switch(property) {
                             case "Sun": LoadLighting(reader); break;
                             case "Ground": LoadTerrain(reader); break;
                             case "Camera": LoadCamera(reader); break;
                             case "Resources": LoadResources(reader); break;
                             case "Players": LoadPlayers(reader); break;
                             default: break;
                         }
                     }
                 }
             }
         }
     }
 }
Пример #40
0
        private async Task ParseStepsAsync(
            Stream stream,
            RecipeDescriptor descriptor,
            Func<RecipeDescriptor, RecipeStepDescriptor, Task> stepActionAsync)
        {
            var serializer = new JsonSerializer();

            StreamReader streamReader = new StreamReader(stream);
            JsonTextReader reader = new JsonTextReader(streamReader);

            // Go to Steps, then iterate.
            while (reader.Read())
            {
                if (reader.Path == "steps" && reader.TokenType == JsonToken.StartArray)
                {
                    int stepId = 0;
                    while (reader.Read() && reader.Depth > 1)
                    {
                        if (reader.Depth == 2)
                        {
                            var child = JToken.Load(reader);
                            await stepActionAsync(descriptor, new RecipeStepDescriptor
                            {
                                Id = (stepId++).ToString(CultureInfo.InvariantCulture),
                                RecipeName = descriptor.Name,
                                Name = child.Value<string>("name"),
                                Step = child
                            });
                        }
                    }
                }
            }
        }
Пример #41
0
 public static ObservableCollection<MediaFile> GetMedia()
 {
     if (File.Exists(libraryCachePath))
     {
         using (var file = File.OpenRead(libraryCachePath))
         using (var sr = new StreamReader(file))
         using (var jtr = new JsonTextReader(sr))
         {
             return new ObservableCollection<MediaFile>(serializer.Deserialize<List<MediaFile>>(jtr));
         }
     }
     else
     {
         var library = RefreshLibrary();
         if (!Directory.Exists(Path.GetDirectoryName(libraryCachePath)))
         {
             Directory.CreateDirectory(Path.GetDirectoryName(libraryCachePath));
         }
         using (var file = File.Open(libraryCachePath, FileMode.Create))
         using (var sw = new StreamWriter(file))
         using (var jtr = new JsonTextWriter(sw))
         {
             serializer.Serialize(jtr, library);
         }
         return new ObservableCollection<MediaFile>(library);
     }
 }
Пример #42
0
    private XmlNode DeserializeXmlNode(string json, string deserializeRootElementName)
    {
      JsonTextReader reader;

      reader = new JsonTextReader(new StringReader(json));
      reader.Read();
      XmlNodeConverter converter = new XmlNodeConverter();
      if (deserializeRootElementName != null)
        converter.DeserializeRootElementName = deserializeRootElementName;

      XmlNode node = (XmlNode)converter.ReadJson(reader, typeof (XmlDocument), null, new JsonSerializer());

#if !NET20
     string xmlText = node.OuterXml;

      reader = new JsonTextReader(new StringReader(json));
      reader.Read();
      XDocument d = (XDocument) converter.ReadJson(reader, typeof (XDocument), null, new JsonSerializer());

      string linqXmlText = d.ToString(SaveOptions.DisableFormatting);
      if (d.Declaration != null)
        linqXmlText = d.Declaration + linqXmlText;

      Assert.AreEqual(xmlText, linqXmlText);
#endif

      return node;
    }
Пример #43
0
 public static Color LoadColor(JsonTextReader reader)
 {
     if (reader == null) return new Color(0, 0, 0, 0);
     Color color = new Color(0, 0, 0, 0);
     string currVal = "";
     while (reader.Read())
     {
         if (reader.Value != null)
         {
             if (reader.TokenType == JsonToken.PropertyName) currVal = (string)reader.Value;
             else
             {
                 switch (currVal)
                 {
                     case "r": color.r = (float)(double)reader.Value; break;
                     case "g": color.g = (float)(double)reader.Value; break;
                     case "b": color.b = (float)(double)reader.Value; break;
                     case "a": color.a = (float)(double)reader.Value; break;
                     default: break;
                 }
             }
         }
         else if (reader.TokenType == JsonToken.EndObject) return color;
     }
     return color;
 }
Пример #44
0
 public object Deserialize(string json)
 {
     using (var reader = new System.IO.StringReader(json))
         using (var jsonReader = new NewtonsoftJson.JsonTextReader(reader))
         {
             return(internalSerializer.Deserialize(jsonReader));
         }
 }
        public override void WriteRawJsonToken(
            JsonTokenType jsonTokenType,
            ReadOnlySpan <byte> rawJsonToken)
        {
            string rawJson = Encoding.UTF8.GetString(rawJsonToken);

            Newtonsoft.Json.JsonTextReader jsonTextReader = new Newtonsoft.Json.JsonTextReader(new StringReader(rawJson))
            {
                DateParseHandling = DateParseHandling.None,
            };

            while (jsonTextReader.Read())
            {
                if (jsonTokenType == JsonTokenType.FieldName)
                {
                    this.writer.WritePropertyName(jsonTextReader.Value as string);
                }
                else
                {
                    switch (jsonTextReader.TokenType)
                    {
                    case Newtonsoft.Json.JsonToken.StartObject:
                        this.writer.WriteStartObject();
                        break;

                    case Newtonsoft.Json.JsonToken.StartArray:
                        this.writer.WriteStartArray();
                        break;

                    case Newtonsoft.Json.JsonToken.PropertyName:
                        this.writer.WritePropertyName(jsonTextReader.Value as string);
                        break;

                    case Newtonsoft.Json.JsonToken.Integer:
                    case Newtonsoft.Json.JsonToken.Float:
                    case Newtonsoft.Json.JsonToken.String:
                    case Newtonsoft.Json.JsonToken.Boolean:
                        this.writer.WriteValue(jsonTextReader.Value);
                        break;

                    case Newtonsoft.Json.JsonToken.Null:
                        this.writer.WriteNull();
                        break;

                    case Newtonsoft.Json.JsonToken.EndObject:
                        this.writer.WriteEndObject();
                        break;

                    case Newtonsoft.Json.JsonToken.EndArray:
                        this.writer.WriteEndArray();
                        break;

                    default:
                        throw new ArgumentOutOfRangeException($"Unknown {nameof(JsonToken)}: {jsonTextReader.TokenType}.");
                    }
                }
            }
        }
        public void DeserializeRequest(Message message, object[] parameters)
        {
            object bodyFormatProperty;

            if (!message.Properties.TryGetValue(WebBodyFormatMessageProperty.Name, out bodyFormatProperty) ||
                (bodyFormatProperty as WebBodyFormatMessageProperty).Format != WebContentFormat.Raw)
            {
                throw new InvalidOperationException("Incoming messages must have a body format of Raw. Is a ContentTypeMapper set on the WebHttpBinding?");
            }

            var bodyReader = message.GetReaderAtBodyContents();

            bodyReader.ReadStartElement("Binary");
            var rawBody = bodyReader.ReadContentAsBase64();
            var ms      = new MemoryStream(rawBody);

            var sr         = new StreamReader(ms);
            var serializer = CreateJsonSerializer(); // new JsonSerializer();

            if (parameters.Length == 1)
            {
                // single parameter, assuming bare
                parameters[0] = serializer.Deserialize(sr, _operation.Messages[0].Body.Parts[0].Type);
            }
            else
            {
                // multiple parameter, needs to be wrapped
                JsonReader reader = new Newtonsoft.Json.JsonTextReader(sr);
                reader.Read();
                if (reader.TokenType != Newtonsoft.Json.JsonToken.StartObject)
                {
                    throw new InvalidOperationException("Input needs to be wrapped in an object");
                }

                reader.Read();
                while (reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName)
                {
                    var parameterName = reader.Value as string;
                    reader.Read();
                    if (_parameterNames.ContainsKey(parameterName))
                    {
                        var parameterIndex = _parameterNames[parameterName];
                        parameters[parameterIndex] = serializer.Deserialize(reader, _operation.Messages[0].Body.Parts[parameterIndex].Type);
                    }
                    else
                    {
                        reader.Skip();
                    }

                    reader.Read();
                }

                reader.Close();
            }

            sr.Close();
            ms.Close();
        }
Пример #47
0
        internal T Load(string identifier, Type objtype)
        {
            var path = Path.Combine(this.Location, identifier);

            using (var jw = new Newtonsoft.Json.JsonTextReader(new System.IO.StreamReader(path)))
            {
                var serializer = Newtonsoft.Json.JsonSerializer.Create();
                return((T)serializer.Deserialize(jw, objtype));
            }
        }
Пример #48
0
 public T Deserialize <T>(Stream stream) where T : class
 {
     using (var sr = new StreamReader(stream))
     {
         using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(sr))
         {
             var serializer = new Newtonsoft.Json.JsonSerializer();
             return(serializer.Deserialize <T>(jsonTextReader));
         }
     }
 }
Пример #49
0
        private List <SelectListItem> LoadCountries()
        {
            var fileInfo = _environment.ContentRootFileProvider.GetFileInfo("countries.json");

            using (var stream = fileInfo.CreateReadStream())
                using (var streamReader = new StreamReader(stream))
                    using (var jsonTextReader = new Newtonsoft.Json.JsonTextReader(streamReader))
                    {
                        var serializer = new JsonSerializer();
                        return(serializer.Deserialize <List <SelectListItem> >(jsonTextReader));
                    }
        }
        private static SalahTimeEntity ReadJsonFile()
        {
            SalahTimeEntity salahTimeEntity = new SalahTimeEntity("First", "Active");

            try
            {
                string currentFile = new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;
                Console.WriteLine(currentFile);
                string dir        = new FileInfo(currentFile).Directory.Parent.FullName;
                string pathToJson = Path.Combine(dir, "SalahTime.json");
                Console.WriteLine(pathToJson);

                using (StreamReader file = File.OpenText(@pathToJson))
                    using (Newtonsoft.Json.JsonTextReader reader = new Newtonsoft.Json.JsonTextReader(file))
                    {
                        JArray jsonResponse = null;
                        try
                        {
                            jsonResponse = (JArray)JToken.ReadFrom(reader);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.Message);
                            Console.WriteLine(ex.StackTrace);

                            // jsonResponse = (JArray)JToken.Parse(ResourceReader.GetEmbeddedResourceString(Assembly.GetExecutingAssembly(), "TestData.json"));
                        }

                        //List<SalahTimeEntity> testDataList = new List<SalahTimeEntity>();

                        //foreach (var item in jsonResponse)
                        //{
                        //    JObject jData = (JObject)item;

                        //    //SalahTimeEntity rowsResult = JsonConvert.DeserializeObject<SalahTimeEntity>(jData.ToString());
                        //    //testDataList.Add(rowsResult);

                        //    salahTimeEntity.JsonForm = jData.ToString();
                        //}

                        salahTimeEntity.JsonForm = jsonResponse.ToString();
                    }

                return(salahTimeEntity);
            }
            catch (Exception ex)
            {
                //Console.WriteLine(ex.Message);
                //Console.WriteLine(ex.StackTrace);

                return(null);
            }
        }
Пример #51
0
        private void ParseResponse(int service, string file, Stream stream)
        {
            object result;

            try
            {
                using (stream)
                {
                    StreamReader networkReader = new StreamReader(stream);
                    string       responseTxt   = networkReader.ReadToEnd();

                    Type type = GetJsonType(service);
                    if (responseTxt.StartsWith("{ \"error\""))
                    {
                        type = typeof(ErrorEventArgs);
                    }
                    if (type == null)
                    {
                        result = responseTxt;
                    }
                    else
                    {
                        Newtonsoft.Json.JsonSerializer serializer = new Newtonsoft.Json.JsonSerializer();
                        serializer.Converters.Add(new MySquare.FourSquare.NotificationConverter());
                        serializer.Converters.Add(new MySquare.Service.DateTimeConverter());
                        //Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(new StreamReader(stream));
                        Newtonsoft.Json.JsonReader reader = new Newtonsoft.Json.JsonTextReader(new StringReader(responseTxt));
                        result = serializer.Deserialize(reader, type);
                    }

                    if (responseTxt.StartsWith("{ \"error\""))
                    {
                        ((ErrorEventArgs)result).Exception = ((ErrorEventArgs)result).Exception;
                    }
                }
            }
            catch (Exception ex)
            {
                OnError(new ErrorEventArgs(new Exception(
                                               string.Format("Request on {0} failed.", file), ex)));
                return;
            }

            if (result != null)
            {
                OnResult(result, service);
            }
            else
            {
                OnError(new ErrorEventArgs(new Exception("Invalid response.")));
            }
        }
Пример #52
0
        private async Task <T> DeserializeStream <T>(RequestExecutionContext context, Stream stream)
        {
            await using var memoryStream = new MemoryStream();

            await stream.CopyToAsync(memoryStream, context.HttpContext.RequestAborted);

            memoryStream.Position = 0;

            using var streamReader = new StreamReader(memoryStream);

            using var jsonReader = new Json.JsonTextReader(streamReader);

            return(JsonSerializer.Deserialize <T>(jsonReader));
        }
Пример #53
0
 public static string JsonPrettify(string json)
 {
     using (var stringReader = new StringReader(json))
         using (var stringWriter = new StringWriter())
         {
             var jsonReader = new Newtonsoft.Json.JsonTextReader(stringReader);
             var jsonWriter = new Newtonsoft.Json.JsonTextWriter(stringWriter)
             {
                 Formatting = Newtonsoft.Json.Formatting.Indented
             };
             jsonWriter.WriteToken(jsonReader);
             return(stringWriter.ToString());
         }
 }
Пример #54
0
        public async Task StartJobAsync()
        {
            using (var syncStartItem = await Web.PostAsync("Start", NullPostContent).ConfigureAwait(false))
            {
                syncStartItem.EnsureSuccessStatusCode();

                using (var stream = await syncStartItem.Content.ReadAsStreamAsync())
                    using (var reader = new Newtonsoft.Json.JsonTextReader(new System.IO.StreamReader(stream)))
                    {
                        var serializer = new Newtonsoft.Json.JsonSerializer();
                        var obj        = serializer.Deserialize <StartSyncJobResponse>(reader);
                        SyncID = obj.id;
                    }
            }
        }
Пример #55
0
        public static T DeserializeJsonFromStream <T>(Stream stream)
        {
            if (stream == null || stream.CanRead == false)
            {
                return(default(T));
            }

            using (var sr = new StreamReader(stream))
                using (var jtr = new Newtonsoft.Json.JsonTextReader(sr))
                {
                    var js           = new Newtonsoft.Json.JsonSerializer();
                    var searchResult = js.Deserialize <T>(jtr);
                    return(searchResult);
                }
        }
Пример #56
0
        private void SendMail()
        {
            MailSecrets mailSecret = null;

            using (var stream = _assembly.GetManifestResourceStream("FindIpAddress.mail_secrets.json"))
            {
                Json.JsonSerializer    serializer   = new Json.JsonSerializer();
                System.IO.StreamReader streamReader = new System.IO.StreamReader(stream);
                Json.JsonTextReader    reader       = new Json.JsonTextReader(streamReader);
                mailSecret = serializer.Deserialize <MailSecrets>(reader);
            }

            var          fromAddress = new MailAddress(mailSecret.Email, mailSecret.Name);
            var          toAddress   = new MailAddress(mailSecret.Email, mailSecret.Name);
            const string subject     = "Adresse";
            string       body        = CheckIpAddress();

            using (var smtp = new SmtpClient())
            {
                smtp.Host                  = "smtp.gmail.com";
                smtp.Port                  = 587;
                smtp.EnableSsl             = true;
                smtp.DeliveryMethod        = SmtpDeliveryMethod.Network;
                smtp.UseDefaultCredentials = false;
                smtp.Timeout               = 10000;
                smtp.Credentials           = new NetworkCredential(fromAddress.Address, mailSecret.Password);

                using (var message = new MailMessage(fromAddress, toAddress))
                {
                    message.Subject    = subject;
                    message.Body       = body;
                    message.IsBodyHtml = true;
                    try
                    {
                        smtp.Send(message);
                        if (this.currentWindowState == System.Windows.WindowState.Normal)
                        {
                            MessageBox.Show("eMail sent", "", MessageBoxButton.OK, MessageBoxImage.Information);
                        }
                    }
                    catch (Exception ep)
                    {
                        MessageBox.Show("Exception Occured:" + ep.Message, "Send Mail Error", MessageBoxButton.OK, MessageBoxImage.Error);
                    }
                }
            }
        }
Пример #57
0
        //private void ViewData()
        //{
        //	HttpWebRequest req = common.connectionGet("people");

        //	HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        //	List<PersonView> result;
        //	using (res)
        //	{
        //		using (var resStream = res.GetResponseStream())
        //		{
        //			StreamReader sr = new StreamReader(resStream);
        //			string str = sr.ReadToEnd();
        //			result = JsonConvert.DeserializeObject<List<PersonView>>(str.ToString());
        //		}
        //	}
        //	ViewGrid.DataContext = common.ConvertToDataTable(result);

        //}

        //private void PostData(PersonView data)
        //{
        //	HttpWebRequest req = common.connectionPost("people");

        //	using (var streamWriter = new StreamWriter(req.GetRequestStream()))
        //	{
        //		string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
        //		streamWriter.Write(json);
        //	}

        //	HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        //	List<PersonView> result = new List<PersonView>();
        //	using (res)
        //	{
        //		using (var resStream = res.GetResponseStream())
        //		{
        //			StreamReader sr = new StreamReader(resStream);
        //			string str = sr.ReadToEnd();
        //			var r = JsonConvert.DeserializeObject<PersonView>(str.ToString());
        //			result.Add(r);
        //		}
        //	}
        //	ViewGrid.DataContext = common.ConvertToDataTable(result);
        //}
        //

        //private void PostDataList(List<PersonView> data)
        //{
        //	HttpWebRequest req = common.connectionPost("people");

        //	using (var streamWriter = new StreamWriter(req.GetRequestStream()))
        //	{
        //		string json = Newtonsoft.Json.JsonConvert.SerializeObject(data);
        //		streamWriter.Write(json);
        //	}

        //	HttpWebResponse res = (HttpWebResponse)req.GetResponse();
        //	List<PersonView> result = new List<PersonView>();
        //	using (res)
        //	{
        //		using (var resStream = res.GetResponseStream())
        //		{
        //			StreamReader sr = new StreamReader(resStream);
        //			string str = sr.ReadToEnd();
        //			var r = JsonConvert.DeserializeObject<PersonView>(str.ToString());
        //			result.Add(r);
        //		}
        //	}
        //	ViewGrid.DataContext = common.ConvertToDataTable(result);
        //}


        //private void Button_Click(object sender, RoutedEventArgs e)
        //{
        //	DataTable table = ViewGrid.DataContext as DataTable;
        //	DataTable list = table.GetChanges();
        //	foreach (PersonView item in list.Rows)
        //	{
        //		PostData(item);
        //	}
        //}
        #endregion



        #region API処理

        private async void GetUserList()
        {
            var hc = new HttpClient();

            hc.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            var res = await hc.GetAsync(common.GetURL() + "people");

            var str = await res.Content.ReadAsStringAsync();

            testMess.Text = str;

            var js    = new Newtonsoft.Json.JsonSerializer();
            var jr    = new Newtonsoft.Json.JsonTextReader(new System.IO.StringReader(str));
            var items = js.Deserialize <List <PersonView> >(jr);

            ViewGrid.ItemsSource = items;
        }
    private IEnumerator TestRequest(string token)
    {
        var uri = "http://cad.onshape.com/api/documents";

        UnityWebRequest www = UnityWebRequest.Get(uri);

        www.SetRequestHeader("Authorization", "Bearer " + token);

        yield return(www.SendWebRequest());


        if (www.isNetworkError || www.isHttpError)
        {
            Debug.LogError(www.error);
            yield return(null);
        }
        else
        {
            Debug.Log(www.downloadHandler.text);
        }
        try
        {
            TextReader sr = new StringReader(www.downloadHandler.text);


            var reader = new Newtonsoft.Json.JsonTextReader(sr);

            var ser  = Newtonsoft.Json.JsonSerializer.Create();
            var docs = ser.Deserialize <IO.Swagger.Model.DocumentsGetDocumentsResponse200>(reader);

            var txt = "";

            foreach (var doc in docs.Items)
            {
                txt += doc.Name + "(Modified by : " + doc.ModifiedBy.Name + " - Created by : " + doc.CreatedBy.Name + ")\r\n";
            }
            Text.text = txt;

            Debug.Log(docs);
        }
        catch (Exception ex)
        {
            Debug.LogError(ex);
        }
    }
Пример #59
0
        public static List <IFigures> Deserilization(string filename)
        {
            var serializer = new Newtonsoft.Json.JsonSerializer
            {
                TypeNameHandling = Newtonsoft.Json.TypeNameHandling.Auto
            };

            List <IFigures> _figure = null;

            using (StreamReader streamReader = new StreamReader(filename))
            {
                using (Newtonsoft.Json.JsonReader jreader = new Newtonsoft.Json.JsonTextReader(streamReader))
                {
                    _figure = serializer.Deserialize <List <IFigures> >(jreader);
                }
            }
            return(_figure);
        }
Пример #60
0
        protected System.Collections.Generic.IEnumerable <JsonLogEntry> GetEntries()
        {
            Newtonsoft.Json.JsonSerializer oJsonSerializer = new Newtonsoft.Json.JsonSerializer();
            foreach (System.Tuple <string, System.IO.Stream> st in StreamFactory.GetStreams(From, this.Recurse))
            {
                this.StreamLineNumber  = 0;
                this.CurrentStreamName = st.Item1;
                this.RecordIndex       = 0;

                using (AdvancedTextReader srdr = new AdvancedTextReader(st.Item2, this.TextReaderOptions))
                {
                    using (var m_JsonReader = new Newtonsoft.Json.JsonTextReader(srdr)
                    {
                        SupportMultipleContent = true
                    })
                    {
                        bool bStartRead = string.IsNullOrEmpty(JsonPropertyToRead);
                        while (m_JsonReader.Read())
                        {
                            if (!bStartRead && !(m_JsonReader.TokenType == JsonToken.PropertyName && m_JsonReader.Value == JsonPropertyToRead))
                            {
                                continue;
                            }
                            else
                            {
                                bStartRead = true;
                            }

                            if (m_JsonReader.TokenType == JsonToken.StartObject)
                            {
                                // Additional fields
                                this.StreamLineNumber = m_JsonReader.LineNumber;
                                this.RecordIndex     += 1;

                                // Deserialize entries and yield
                                JsonLogEntry le = oJsonSerializer.Deserialize <JsonLogEntry>(m_JsonReader);
                                yield return(le);
                            }
                        }
                    }
                }
            }
        }